Leetcode: Find Peak Element
This question is commonly asked at big companies such as Facebook, Amazon, and Google. It is as follows:
A peak element is an element that is strictly greater than its neighbors. Now all we have to do is to return a peak index. That's it. So let's get into it. We can imagine that the nums are -∞.
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
We want to do this in O(log n) time.
What we do want is to do a binary tree search and make sure the left and right element is greater than or less than some other element.
We get a middle element. And then go to either the left and right side based on whether the mid value is a peak or not until we reached the edge where the left has surpassed the right, then we stop. We assume the edge cases are minimum, so there's no peak over there. Here's the code:
class Solution {
public int findPeakElement(int[] nums) {
int left = 0;
int right = nums.length - 1;
while(left < right) {
int mid = (left + right) / 2;
if(nums[mid] < nums[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}


Comments
Post a Comment