【题目描述】
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.
1.遍历然后判断是否比前后元素都大,是则输出该元素下标,注意的是对第一个和最后一个元素要分开来判断。
2.因为题目的tag是binary search,所以用二分也实现了一遍,虽然我觉得没什么必要,耗时也是8ms,和第一种方法一样的。
【代码】
1.
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if(nums.size()==0||nums.size()==1) return 0;
for(int i=0;i<nums.size();i++){
if(i==0){
if(nums[i]>nums[i+1]) return i;
}
if(i==nums.size()-1){
if(nums[i]>nums[i-1]) return i;
}
if(nums[i-1]<nums[i]&&nums[i]>nums[i+1]) return i;
}
}
};
2.
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int low=0;
int high=nums.size();
while(low<high){
int mid=(low+high)>>1;
if(mid<nums.size()-1&&nums[mid]<nums[mid+1]) low=mid+1;
else if(mid>=1&&nums[mid]<nums[mid-1]) high=mid;
else return mid;
}
return low;
}
};