标签:
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.
Your solution should be in logarithmic complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Array Binary Search
#include <vector> #include <iostream> using namespace std; class Solution { public: int findPeakElement(const vector<int> &num) { int n = num.size(); if(n==3&&num[0]<num[1]&&num[1]>num[2]) return 1; if(n<2) return 0; if(num[0]>num[1]) return 0; if(num[n-2]<num[n-1]) return n-1; return help_fun(num,0,num.size()-1); } int help_fun(const vector<int> &num,int lft,int rgt) { int n = num.size(); if(rgt - lft <2){ if(lft!=0&&num[lft-1]<num[lft]&&num[lft]>num[lft+1]) return lft; if(rgt!=n-1&&num[rgt-1]<num[rgt]&&num[rgt]>num[rgt+1]) return rgt; return -1; } int mid = (lft+rgt)/2; if(num[mid-1]<num[mid]&&num[mid]>num[mid+1]) return mid; int ascend = -1; if(num[mid-1]<num[mid]&&num[mid]<num[mid+1]) ascend = 1; if(num[mid-1]>num[mid]&&num[mid]>num[mid+1]) ascend = 0; if(ascend==1&&num[mid]>=num[rgt]) return help_fun(num,mid,rgt); if(ascend==0&&num[lft]<-num[mid]) return help_fun(num,lft,mid); int retlft = help_fun(num,lft,mid); if(retlft!=-1) return retlft; return help_fun(num,mid,rgt); } }; int main() { vector<int > num{3,1,2}; Solution sol; cout<<sol.findPeakElement(num)<<endl; return 0; }
[LeetCode] Find Peak Element 二分搜索
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4333056.html