L162 Find Peak Valley Element
Binary Search
Problem
A peak element is an element that is greater than its neighbors.
Given an input array nums
, where nums[i] ≠ nums[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞
.
Example:
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.
Solution:
we should consider two conditions:
mid-1 < mid < mid+1, if so return mid;
mid-1 < mid && mid -1 >= 0, which means currently, mid is at left of the peak, so left move to the mid and get new mid which will move to right.
public int findPeak(int arr){
if(arr == null || arr.length == 0) return -1;
int left = 0, right = arr.length - 1;
while(left + 1 < right){
int mid = left + (right - left)/2;
if(arr[mid] < arr[mid+1]) && arr[mid] > arr[mid-1]){
return mid;
}else if(mid - 1 >= 0 && arr[mid] > arr[mid-1]){
left = mid;
}else{
right = mid;
}
}
return arr[left] > arr[right] ? left: right;
}
Last updated
Was this helpful?