`

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.

按照题目的要求,从一个数组中找到一个数比它的邻居都大。数组有几个特征,没相邻的两个元素不同,并且题目中假设num[-1] = num[n] = -∞。这样我们可以确定的是除非数组为空,否则数组中肯定会存在一个peak element。我们可以用二分法,从中间元素开始比较,如果nums[m] > nums[m + 1]说明m + 1左边肯定存在peak元素,我们就从左部分找;如果nums[m] < nums[m + 1]说明m右边肯定存在peak元素,我们从右半部分查找。这样时间复杂度为O(nlogn)。代码如下:
public class Solution {
    public int findPeakElement(int[] nums) {
        if(nums == null || nums.length == 0) return -1;
        if(nums.length == 1) return 0;
        int l = 0;
        int r = nums.length - 1;
        while(l < r) {
            int m = l + (r - l) / 2;
            if(nums[m] > nums[m + 1]) {
                r = m;
            } else {
                l = m + 1;
            }
        }
        return l;
    }
} :twisted: 
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics