162 Find Peak Element

思路:

  1. 暴力法: 每個值也search
  2. Binary Search: 當nums[mid] > nums[mid +1] , 左邊 nums[0] 至nums[mid] 必然存在peak element
    別人代碼:1
Binary Search:

class Solution {
    public int findPeakElement(int[] nums) {
        int left = 0;
        int N = nums.length;
        int right = N - 1;

        while (right - left > 1) {
            int mid = (right + left) / 2;
            if (nums[mid] < nums[mid + 1]) {
                left = mid + 1;
            }else{
                right = mid;
            }
        }

        return (left == N - 1 || nums[left] > nums[left + 1]) ? left : right;
    }
}

別人代碼2:

public int findPeakElement(int[] nums) {
        if (nums.length == 1) {
                return 0;
        }
        int low = 0;
        int high = nums.length - 1;
        int mid;
        while (true) {
            // update mid
            mid = low + (high - low)/2;
            //two corner cases: when mid is the first and the last index
            if (mid == 0 ) {
                if (nums[mid] > nums[mid + 1])
                    return mid;
                else
                    return mid + 1;
            } 
            if (mid == nums.length - 1) {
                if (nums[mid] > nums[mid-1])
                    return mid;
                else
                    return mid -1;
            } 
            //if mid is peak, return mid
            if (nums[mid] > nums[mid-1] && nums[mid] > nums[mid + 1]) {
                return mid;
            }
            //if mid is less than mid - 1 element, look for the peak in the left half
            if (nums[mid] < nums[mid - 1]) {
                high = mid - 1;
            }
            //if mid is less than mid + 1 element, then look for the right half
            else if (nums[mid] < nums[mid + 1]){
                low = mid + 1;
            }
        }
    }

你可能感兴趣的:(162 Find Peak Element)