Friday, March 25, 2016

LeetCode Q162: Find Peak Element

A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Soluton:
Binary search



class Solution {
public:
int findPeakElement(vector<int>& nums) {
if(nums.size()!=0&&(nums[0]>nums[1]))
return 0;
if(nums.size()!=0&&(nums[nums.size()-1]>nums[nums.size()-2]))
return nums.size()-1;
if(nums.size()==1)
return 0;
int l=1;
int r=nums.size()-2;
while(l<r){
int mid=(l+r)/2;
if(nums[mid]>nums[mid-1]&&nums[mid]>nums[mid+1])
return mid;
if(mid==l||mid==r){
mid = nums[l]>nums[r]? l:r;
return mid;
}
if(nums[mid]>nums[mid-1])
l=mid;
else
r=mid;
}
return l;
}
};
view raw Q162.cpp hosted with ❤ by GitHub


Round 2 Solution:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int l=0, r=nums.size()-1;
while(l<r-1){
int mid = (l+r)/2;
int ml = mid==0? INT_MIN:nums[mid-1];
if(nums[mid]>ml)
l=mid;
else
r=mid;
}
return nums[l]<nums[r]? r:l;
}
};
view raw Q162Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment