*LeetCode-Find Peak Element

brute force每个和后面的数字比 找到不增长的那个 o(n)

public class Solution {
    public int findPeakElement(int[] nums) {
        if ( nums == null || nums.length < 2)
            return 0;
        for ( int i = 0; i < nums.length - 1; i ++ ){
            if ( nums[i+1] < nums[i] )
                return i;
        }
        return nums.length-1;
    }
}

binary search logn

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


你可能感兴趣的:(*LeetCode-Find Peak Element)