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.
Soluton:
Binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
Round 2 Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
No comments:
Post a Comment