首页 > 其他 > 详细

162. Find Peak Element

时间:2020-03-21 14:21:32      阅读:50      评论:0      收藏:0      [点我收藏+]

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

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 };

 

162. Find Peak Element

原文:https://www.cnblogs.com/habibah-chang/p/12538950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!