Original title Link: https://oj.leetcode.com/problems/find-peak-element/
Topic: Given an array of unequal adjacent elements, find one of the local maximum value , return the corresponding subscript.
Method 1: Sequential traversal.
An important feature of the subject is that, starting with the first element, if it is larger than the next successive element, the first element is a local maximum value, which is returned. If it is less than the next successive element, the second element is greater than the first element. So, one by one times the first occurrence of the group, if the element i is greater than its adjacent subsequent elements, then the element is a local maximum value, return. The code is as follows:
Class Solution {public: int findpeakelement (const vector<int> &num) {for (int i=1;i<num.size (); I + +) { if (num[i]<num[i-1]) return i-1; } Return Num.size ()-1; }};
Time complexity: Worst O (N)
Method 2: Two-point lookup
Idea: If the intermediate element is larger than its adjacent successive elements, the left side of the intermediate element (containing the intermediate element) must contain a local maximum value. If the intermediate element is smaller than its adjacent successive elements, the right side of the intermediate element must contain a local maximum value.
Class Solution {public: int findpeakelement (const vector<int> &num) { int left=0,right=num.size ()-1 ; while (left<=right) { if (left==right) return to left ; int mid= (left+right)/2; if (num[mid]<num[mid+1]) left=mid+1; else Right=mid;}} ;
Complexity of Time: O (LgN)
The title is good, is binary search continuation, can and binary search related algorithms together to do a summary.
Find Peak Element--leetcode