162. Find Peak Element【medium】
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.
click to show spoilers.
Note:
Your solution should be in logarithmic complexity.
解法一:
1 class Solution { 2 public: 3 int findPeakElement(const vector<int> &num) { 4 for (int i = 1; i < num.size(); i++) { 5 if (num[i] < num[i - 1]) { 6 return i - 1; 7 } 8 } 9 10 return num.size() - 1; 11 } 12 };
直接顺序遍历
解法二:
1 class Solution { 2 public: 3 int findPeakElement(vector<int>& nums) { 4 int start = 0; 5 int end = nums.size() - 1; 6 7 while (start + 1 < end) { 8 int mid = (end - start) / 2 + start; 9 10 if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) { 11 return mid; 12 } 13 /* 如果中间的数比后一位数大的话,peek点肯定在mid左边或是mid */ 14 else if (nums[mid] > nums[mid + 1]) { 15 end = mid; 16 } 17 /* 如果中间的数比前一位数小的话,peek点肯定在mid右边或是mid */ 18 else { 19 start = mid; 20 } 21 } 22 23 return nums[start] > nums[end] ? start : end; 24 } 25 };
二分查找