162. Find Peak Element

问题:求数组的任意峰值。两侧都从-∞开始向上递增。

Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.


Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.

  

方法:二分查找

low=0,high=end

mid=low和high的中值

如果mid<mid+1,则要求目标在mid+1~high

如果mid>mid+1,则要求目标在low~mid

 

代码参考:

 1 class Solution {
 2 public:
 3     int findPeakElement(vector<int>& nums) {
 4         int low=0, high=nums.size()-1;
 5         while(low<high){
 6             int mid=low+(high-low)/2;
 7             if(nums[mid]>nums[mid+1]){
 8                 high=mid;
 9             }else{
10                 low=mid+1;
11             }
12         }
13         return low;
14     }
15 };

 

posted @ 2020-03-21 13:27  habibah_chang  阅读(134)  评论(0)    收藏  举报