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;
        }
    }
  • 相关阅读:
    结构体
    指针
    数组
    银行取款机系统
    函数
    基础
    IOS系统的安装和Vi的操作模式以及简单的指令
    1203.4——循环语句 之 for
    1203.3——循环语句 之 while
    1203.2——条件语句 之 switch语句
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4695356.html
Copyright © 2011-2022 走看看