[LeetCode]Find Peak Element

来源:互联网 发布:商品条码数据库 编辑:程序博客网 时间:2024/06/06 08:30
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.

思路1: 遍历,O(N)
代码1:

    public int findPeakElement1(int[] num) {//暴力        for(int i = 0; i < num.length; ++i){            if(i+1 < num.length){                if(num[i] > num[i+1] && ((i -1 >= 0 && num[i] > num[i-1])||(i-1 < 0))){                    return i;                }            }else {                if(i-1 < 0 || i -1 >=0 && num[i] > num[i-1]){                    return i;                }            }        }        return 0;    }
思路2:二分,
代码:
    public int findPeakElement(int[] num) {//        int l = 0, r = num.length - 1, mid;        while (l < r){            mid = l + (r - l) / 2;            if(num[mid] < num[mid + 1]) l = mid + 1;            else r = mid;        }        return num[l];    }



1 0
原创粉丝点击