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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

第一种:

常规方法:依次遍历,O(n)

public class Solution {
    public int findPeakElement(int[] num) {
        
        for(int  i = 0 ; i < num.length - 1; i++){
            if(num[i] > num[i + 1]){
                return i;
            }
        }
        return num.length-1;
    }
}
Runtime:  416 ms
第二种,二分法

public class Solution {
    public int findPeakElement(int[] num) {
        
        int low = 0;
        int high = num.length -1;
    
        while(low < high){
            int mid = (low + high )/2;
            if(num[mid] < num[mid +1]){
                low = mid + 1;
            }else{
                high = mid;
            }
        }
        return low;
    }
}

Runtime:  432 ms

java中最好的乘积是300多 ms,实在想不到更高效的方法,用随机数自己验证没有问题,但是向网站提交总是提示index越界,贴出来玩玩

public class Solution {
    public int findPeakElement(int[] num) {
        int n = 0;
        while(true){
            n = (int)(Math.random()*num.length);
            if(n != 0 && n != (num.length - 1)){
                if(num[n - 1] < num[n] && num[n] > num[n + 1]){
                    return n;
                }
            }else if(n == 0){
                if(num[n] > num[n + 1]){
                    return n;
                }
            }else if(n == num.length -1){
                if(num[n-1]<num[n]){
                    return n;
                }
            }
        }
    }
}


你可能感兴趣的:(LeetCode,element,find,peak)