[LeetCode]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.

思路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];
    }



發佈了83 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章