Find Peak Element

来源:互联网 发布:淘宝自动充值赚钱吗 编辑:程序博客网 时间:2024/06/17 13:07

https://oj.leetcode.com/problems/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.

public int findPeakElement(int[] num)

事实上这就是要找一个a[i],这个a[i] > a[i - 1] && a[i] > a[i + 1],最直接的O(N)的做法当然就是直接遍历一遍数组找就是了。

但是这样真的是最优解么?很显然不是的。那么在O(N)以下,我们凡人又能够瞬间懂的做法其实只有一个了,那就是binary search了。。

这一题给的条件非常的充裕,num[i] != num[i + 1],任何相邻的数字不相等,返回的又是任意一个peak即可。那么实际上除去极大点以外,可以认为只剩下两种状态了:1.现在处于递增。2.或者递减。 很容易考量的就是如果处于递增,则当前位置右半部分肯定有一个peak(因为num[-1] = num[n] = 负无穷),处于递减,左半部分肯定有一个peak。这题可以做的很难,但是加上那么多条件之后就变得很容易考虑了。基于上面描述的,给出代码如下:

    public int findPeakElement(int[] num) {        int head = 0, tail = num.length - 1;        while(head <= tail){            int mid = (head + tail) / 2;            if(mid > 0 && num[mid] <= num[mid - 1]){//递减                tail = mid - 1;            }else if(mid < num.length - 1 && num[mid] <= num[mid + 1])//递增                head = mid + 1;            else//找到了                return mid;        }        return head;    }


0 0