QUESTION
A peak element is an element, which is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, the find a peak element and return its index.
The array may be contain multiple peaks, in this case return the index to any one of the peaks is fine.
May imagine 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.
1st TRY
The time complexity to reach O (Logn) must be divided into a method of treatment.
If ARRAY[MID-1] is greater than array[mid], the left sub-array Array[start: MID-1] There must be a peak element (because Array[start] is always greater than the left element); Similarly, if array[mid+1] is greater than array[mid], then the sub-array of edges array[mid+1..end] must have peak Element (because Array[end] is always greater than the right).
classSolution { Public: intFindpeakelement (Constvector<int> &num) { returnBinarySearch (NUM,0, Num.size ()-1); } intBinarySearch (Constvector<int> &num,intStartintend) { if(End-start <=1) { if(Num[start]>num[end])returnstart; Else returnend; } intMid = (start+end) >>1; if(Num[mid] > num[mid+1])returnbinarysearch (num, start, mid); Else returnBinarySearch (num, mid+1, end); }};
result:accepted
Find Peak Element (Array-devide-and-conquer)