和best time to buy and sell stock中的某个题类似。
思路很简单:在Binary Search上略加修改。规则是:只要mid比其左邻居小,那说明左半段必然存在peak,只访问左半段即可;否则,右半段必然存在peak。需要注意的是,两端也可以是peak。
1 class Solution { 2 public: 3 int findPeakElement(const vector<int> &num) { 4 int n=num.size(); 5 int left=0,right=n-1; 6 while(left<=right) 7 { 8 int mid=left+(right-left)/2; 9 if((mid==0||num[mid]>num[mid-1])&&(mid==n-1||num[mid]>num[mid+1])) 10 return mid; 11 if(mid>0&&num[mid-1]>num[mid])//mid>0不要忘记 12 right=mid-1; 13 else left=mid+1; 14 } 15 } 16 };