Find Peak Element, findpeakelement
Original question link: https://oj.leetcode.com/problems/find-peak-element/
Given an array with unequal adjacent elements, find a local maximum and return the corresponding subscript.
Method 1: sequential traversal.
An important feature of this question is that, starting from the first element, if it is greater than the adjacent subsequent element, the first element is a local maximum value and can be returned. If it is smaller than the adjacent subsequent element, the second element is greater than the first element. In this way, the array is traversed one by one. If the first element is larger than its adjacent subsequent element, the element is a local maximum value and can be returned. 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: Binary Search
Idea: If the intermediate element is greater than its adjacent subsequent element, the left side of the intermediate element (including the intermediate element) must contain a local maximum value. If the intermediate element is smaller than its adjacent subsequent element, 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 left; int mid=(left+right)/2; if(num[mid]<num[mid+1]) left=mid+1; else right=mid; } }};
Time Complexity: O (lgN)
The question is good. It is a continuation of binary search and can be summarized together with the binary search algorithm.