码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Find Peak Element 二分搜索

时间:2015-03-12 18:51:54      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

Hide Tags
 Array Binary Search
 
 
    这题其实是二分搜索的变形,考虑清楚 left  mid  right  取值的情况,结合判断 mid及其左右构成的升降序来剪枝。
 
 
#include <vector>
#include <iostream>
using namespace std;

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        int n = num.size();
        if(n==3&&num[0]<num[1]&&num[1]>num[2])   return 1;
        if(n<2)    return 0;
        if(num[0]>num[1])   return 0;
        if(num[n-2]<num[n-1])   return n-1;
        return help_fun(num,0,num.size()-1);
    }
    int help_fun(const vector<int> &num,int lft,int rgt)
    {
        int n = num.size();
        if(rgt - lft <2){
            if(lft!=0&&num[lft-1]<num[lft]&&num[lft]>num[lft+1])
                return lft;
            if(rgt!=n-1&&num[rgt-1]<num[rgt]&&num[rgt]>num[rgt+1])
                return rgt;
            return -1;
        }
        int mid = (lft+rgt)/2;
        if(num[mid-1]<num[mid]&&num[mid]>num[mid+1])    return mid;
        int ascend = -1;
        if(num[mid-1]<num[mid]&&num[mid]<num[mid+1]) ascend = 1;
        if(num[mid-1]>num[mid]&&num[mid]>num[mid+1]) ascend = 0;
        if(ascend==1&&num[mid]>=num[rgt])
            return help_fun(num,mid,rgt);
        if(ascend==0&&num[lft]<-num[mid])
            return help_fun(num,lft,mid);
        int retlft = help_fun(num,lft,mid);
        if(retlft!=-1)  return retlft;
        return help_fun(num,mid,rgt);
    }
};

int main()
{
    vector<int > num{3,1,2};
    Solution sol;
    cout<<sol.findPeakElement(num)<<endl;
    return 0;
}

 

[LeetCode] Find Peak Element 二分搜索

标签:

原文地址:http://www.cnblogs.com/Azhu/p/4333056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!