162. Find Peak Element

2018-04-09  本文已影响4人  衣介书生

题目分析

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.

解决这道题的思路是二分查找,时间复杂度为 O(log(n)), 空间复杂度为 O(1)。

代码

class Solution {
    public int findPeakElement(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int start = 0;
        int end = nums.length - 1;
        while(start + 1 < end) {
            int mid = (end - start) / 2 + start;
            if(nums[mid] > nums[mid + 1]) {
                // mid 位置对应的值可能为极大值
                end = mid;
            } else {
                // mid 位置对应的值不可能为极值,mid + 1 对应的值可能为极值
                start = mid + 1;
            }
        }
        if(nums[start] > nums[end]) return start;
        return end;
    }
}
上一篇下一篇

猜你喜欢

热点阅读