A peak element is an element that is strictly greater than its neighbors.
Given an integer array
You may imagine that
Given an integer array
nums
, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.You may imagine that
nums[-1] = nums[n] = -∞
.Example 1:
Input: nums ={1,2,3,1}
Output: 2
Approach
Java
public class FindPeakElement {public static void main(String[] args) {int[] nums = { 1, 2, 3, 1 };System.out.println(findPeakElement(nums));}// method to find the peak element in the arraystatic int findPeakElement(int[] nums) {int n = nums.length;int low = 0, high = n - 1;while (low < high) {int mid = low + (high - low) / 2;if (nums[mid] > nums[mid + 1])high = mid;elselow = mid + 1;}return low;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the peak element in the//arrayint findPeakElement(vector<int> &nums){int n = nums.size();int low = 0, high = n - 1;while (low < high){int mid = low + (high - low) / 2;if (nums[mid] > nums[mid + 1])high = mid;elselow = mid + 1;}return low;}int main(){vector<int> nums = {1, 2, 3, 1};cout << findPeakElement(nums);return 0;}
No comments:
Post a Comment