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;
        }
    }
  • 相关阅读:
    c语言中的数据变量类型,大小
    表达式* ptr ++和++ * ptr是否相同?
    再论i++ ++i
    Chapter 1 First Sight——2
    如何修改博客样式
    PAT1011
    Chapter 1 First Sight——1
    Preface
    L11,one good turn deserves another
    PAT1010
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4695356.html
Copyright © 2011-2022 走看看