Find Peak element leetcode

weixin_33806914發表於2016-01-12

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.

遍歷法

思路

遍歷陣列, 如果一個數大於他的左右兩邊, 那麼就是peak element

複雜度

時間O(n) 空間 O(1)

程式碼

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

二分法

思路

如果一個數小於他左邊的數說明正在下坡, peak element在左邊; 如果小於右邊的數說明正在上坡, peak 在右邊. 另外一種情況就是它即不小於左邊也不小於右邊, 此時本身就是peak element

複雜度

時間O(logn) 空間O(1)

程式碼

public int findPeakElement(int[] nums) {
    int left = 0, right = nums.length - 1;
    while (left + 1 < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] < nums[mid - 1]) {
            right = mid;
        } else if (nums[mid] < nums[mid + 1]) {
            left = mid;
        } else {
            return mid;
        }
    }
    if (nums[left] > nums[right]) {
        return left;
    } else {
        return right;
    }
}

相關文章