Given an array, assume that the left side of subscript 0 is negative infinity, and the subscript size is also negative infinity. Find the peak.
Peak is certain, because the subscript 0 is greater than the left, if not exist then subscript 1 will be greater than 0, one analogy and the next will be greater than the previous. Then know size-1 time is greater than size-2, and because size is negative infinity, then size-1 is the peak. So the peak must exist.
The most down is: each word and left and right comparison, in line with the output subscript. Boundary conditions to judge. About 2n times.
Better: Because we know that 0 of the underlying is already greater than the left, so as long as the 0 start to the right, find the value is greater than the right side of the line, then the judgment N times on the line.
classSolution { Public: intFindpeakelement (Constvector<int> &num) { for(inti =0; I < num.size ()-1; i++) { if(Num[i] > num[i+1]) returni; } returnNum.size ()-1; }};
The best part is: dichotomy, if the left or right side of the mid is bigger than it, then look for the big side of the line.
This is what I wrote:
Feel a slight setback
classSolution { Public: intFindpeakelement (Constvector<int> &num) { intleft =0, right = Num.size ()-1, Mid; if(num.size () = =1)return 0; while(Left <Right ) {Mid= (left + right)/2; if(Mid = = left && Num[left] > Num[right])returnLeft ; Else if(Mid = = left && Num[left] < Num[right])returnRight ; if(Num[mid] > num[mid-1] && Num[mid] > num[mid+1]) returnmid; Else if(Num[mid] < num[mid-1]) right= Mid-1; Else if(Num[mid] < num[mid+1]) left= Mid +1; } returnLeft ; }};
View Code
This is the better one to see:
intFindpeakelement (Constvector<int> &num) { intleft=0, Right=num.size ()-1; while(left<=Right ) { if(left==Right )returnLeft ; intMid= (left+right)/2; if(num[mid]<num[mid+1]) left=mid+1; Else Right=mid; } }
LEETCODE[162] Find Peak Element