Find Peak Element
Description:
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.
Code:
1 //解法1:顺序查找 2 int findPeakElement(vector<int>& nums) { 3 size_t n = nums.size(); 4 assert (n!=0); 5 6 if (n==1 || nums[0] > nums[1]) 7 return 0; 8 9 if (nums[n-1] > nums[n-2]) 10 return n-1; 11 12 for (int i = 1; i <= n-2; ++i) 13 { 14 if (nums[i-1] < nums[i] && nums[i] > nums[i+1] ) 15 return i; 16 } 17 return -1; 18 }
//解法2:二分查找 int findPeakElement(vector<int>& nums) { int left = 0; int right = nums.size()-1; while (left < right) { int mid = (left + right)/2; if (nums[mid]<nums[mid+1]) left = mid+1;//mid右边一定存在山峰 else right = mid;//mid左边一定存在山峰 } return left; }