zoukankan      html  css  js  c++  java
  • [leedcode 162] 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.

    public class Solution {
        public int findPeakElement(int[] nums) {
            //利用抛物线的知识,因为nums[-1]=nums[n]=-∞,所以抛物线存在极值点
            //传统的办法时间复杂度O(n),二分法时间复杂度O(lgn)
            //分别就mid处在极值点左边还是右边进行分开处理,注意递归的终止条件——是只剩两个点
            if(nums==null||nums.length<=0) return -1;
            int res=find(nums,0,nums.length-1);
            return res;
        }
        public int find(int[] nums,int start,int end){
            if(end-start<=1){
                return nums[start]>nums[end]?start:end;
            }
            int mid=(start+end)/2;
            if(nums[mid]>nums[mid+1]&&nums[mid]>nums[mid-1])return mid;
            if(nums[mid]<nums[mid+1]) return find(nums,mid+1,end);
            if(nums[mid]>nums[mid+1]) return find(nums,start,mid-1);
            return -1;
        }
    }
  • 相关阅读:
    brew
    hbase
    YARN常见问题以及解决方案
    mybatis中foreach collection三种用法
    mysql按分隔符输出多行
    mysql DATETIME
    iis 之给网站添加MIME映射
    VS2019专业版和企业版激活密钥
    ViewData对于从后台传list到前台的使用
    找出每组数据中不同distinct
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4695356.html
Copyright © 2011-2022 走看看