Find Peak Element(Medium)

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. 如果数组的middle元素是peak,直接返回middle。
  2. If the left neighbor is greater than the middle, move to the left. The peak element must exist in the left half. That is because the num[-1] = num[n] = -inf.
  3. The same, if the right neighbor is greater than the middle, move to the right.

Java代码

public int findPeakElement(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }

    int lo = 0;
    int hi = nums.length - 1;

    while (lo + 1 < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
            return mid;
        } else if (nums[mid - 1] > nums[mid]) {
            hi = mid;
        } else if (nums[mid + 1] > nums[mid]) {
            lo = mid;
        }
    }

    if (nums[hi] >= nums[lo]) {
        return hi;
    } else {
        return lo;
    }
}

results matching ""

    No results matching ""