现在的位置: 首页 > 综合 > 正文

leetcode——Find Peak Element

2017年12月22日 ⁄ 综合 ⁄ 共 958字 ⁄ 字号 评论关闭

题目:

A peak element is an only 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.

Note:

Your solution should be in logarithmic complexity.

思路:

题目中要找到比两边相邻的数字都大的数(峰值),而且在序列中有且仅有一个这样的数。

首先来建模,对于题目中的描述,不禁想到了y=-(x-a)^2+b的函数图像。

在题目中看来,不过是a有可能是所给数组的第一个或者最后一个值。

而对于仅仅有一个峰值的函数来说,峰值两边导数相反,而且峰值左边导数为正,右边为负。

因此为了达到logn的时间复杂度,可以进行二分法,即,分割之后若一边的导数为正,则峰值在另一边;反之亦然;知道刚好在分割的中点为峰值,则结束运算。

AC代码:

public int findPeakElement(int[] num) {
        if (num.length==1){
            return 0;
        }
        if(num[0]>num[1])
            return 0;
        if(num[num.length-1]>num[num.length-2])
            return num.length-1;

        int left = 1,right = num.length-2;
        while(left<=right){
            int mid = (left+right)>>1;
            if(num[mid]>num[mid-1] && num[mid]>num[mid+1]){
                return mid;
            }
            else if(num[mid]>num[mid-1]){
                left = mid+1;
            }
            else{
                right = mid-1;
            }
        }
        return -1;
    }

抱歉!评论已关闭.