[LeetCode] 162. Find Peak Element

求数组的局部峰值。给一个数组,数组满足条件nums[i] ≠ nums[i+1],求数组峰值的下标。例子

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.

思路是用二分法,因为题目要求时间复杂度是log级别。

时间O(logn)

空间O(1)

/**
 * @param {number[]} nums
 * @return {number}
 */
var findPeakElement = function(nums) {
    let start = 0;
    let end = nums.length - 1;
    while (start + 1 < end) {
        let mid = Math.floor(start + (end - start) / 2);
        if (nums[mid] > nums[mid + 1]) {
            end = mid;
        } else {
            start = mid;
        }
    }
    if (nums[start] > nums[end]) return start;
    return end;
};

相关推荐