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;
    }
  • 相关阅读:
    “三路九招”打赢电商低成本营销战
    我的文章分类
    ResourceBundle读取中文properties文件问题
    敏捷基础知识
    一个简单方法:构造xml的document,并将其转换为string
    在android源码环境下写上层应用的一个初步解决方法
    Linux 与 unix shell编程指南——学习笔记
    git 分支的基本操作
    使用repo的本地开发流程
    Linux常用命令收集
  • 原文地址:https://www.cnblogs.com/Azhu/p/4333056.html
Copyright © 2011-2022 走看看