美文网首页
162. Find Peak Element

162. Find Peak Element

作者: 衣介书生 | 来源:发表于2018-04-09 21:28 被阅读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;
    }
}

相关文章

网友评论

      本文标题:162. Find Peak Element

      本文链接:https://www.haomeiwen.com/subject/otjwhftx.html