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.
题目大意:给定一个数组,数组中相邻的元素互不相同,找出peak element ,所谓的peak element是指比左相邻、右相邻元素都大的那个元素(第一个元素只需考虑右相邻,最后一个元素只需考虑左相邻)。当数组中有多个peak element 时,随便返回一个(题目要求返回的是元素在数组中的下标)。
这道题目没什么复杂的,最简单的解法就是从头到尾扫描一遍数组,碰到peak element 就返回它的下标。前面已经说了,peak element的判断无非就是比左相邻、右相邻元素都大。这个方法时间复杂度是O(n)。代码见3.
class Solution { public: int findPeakElement(const vector<int> &num) { int len=num.size(); for(int i=1;i<len-1;i++){ if(num[i]>num[i+1]&&num[i]>num[i-1]){ return i; } } if(num[0]>num[1]) return 0; if(num[len-1]>num[len-2]) return len-1; } };
class Solution { public: int findPeakElement(const vector<int> &num) { return findPeakElement(num,0,num.size()-1); } private: int findPeakElement(const vector<int> &num,int start,int end){ if (start==end) return start; if(end-start==1) return num[start]>num[end]?start:end; int mid=(end+start)/2; if(num[mid]>num[mid-1]&&num[mid]>num[mid+1]) return mid; else if(num[mid]<num[mid-1]) return findPeakElement(num,start,mid-1); else return findPeakElement(num,mid+1,end); } };