zoukankan      html  css  js  c++  java
  • [LeetCode] Find Peak Element 二分搜索

    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;
    }
  • 相关阅读:
    django开发之model篇-Field类型讲解
    Scrapy+Chromium+代理+selenium
    如何在 CentOS 7 上安装 Python 3
    分享几个简单的技巧让你的 vue.js 代码更优雅
    如何用纯 CSS 创作一副国际象棋
    如何用纯 CSS 创作一个文本淡入淡出的 loader 动画
    Java8中数据流的使用
    SpringBoot中使用mybatis-generator自动生产
    Git 同时与多个远程库互相同步
    记录Java中对url中的参数进行编码
  • 原文地址:https://www.cnblogs.com/Azhu/p/4333056.html
Copyright © 2011-2022 走看看