关闭

Leetcode 162. Find Peak Element

标签: Binary Search
116人阅读 评论(0) 收藏 举报
分类:

162. Find Peak Element

Total Accepted: 78108 Total Submissions: 227653 Difficulty: Medium

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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

思路:

一开始以为找全局最大的peak点,然后写了一个遍历数组一遍同时记下peak元素和index位置的代码,一提交居然accept了。。

public class Solution {
    public int findPeakElement(int[] nums) {
        if(nums.length == 1) return 0;
        
        int peak = Integer.MIN_VALUE, index = -1, last = nums.length - 1;
        if(nums[0] > nums[1]) { index = 0; peak = nums[0]; }
        if(nums[last] > nums[last-1] && nums[last] > peak) { index = last; peak = nums[last]; }
        
        for(int i = 1; i <= last-1; i++){
            if(nums[i-1] < nums[i] && nums[i] > nums[i+1]){
                if(nums[i] > peak){
                    index = i; peak = nums[i];
                }
            }
        }
        return index;
    }
}


然后一看要求,要求log时间,不对啊,全局最大peak怎么可能log。再仔细一看,返回一个peak元素index就行。。

所以可以用binary search,取中点,然后对比它(mid)和mid+1位置元素大小(因为除法取小,有可能取到0,不能-1会越界),如果mid小,说明mid+1到end必出peak元素(看下面):

这题有bug,感觉就是为了考二分查找编的题,比如你把输入换成:[1,2,3,3] 就给出错误答案


别忘记判断两边的数字。

public class Solution {
    public int findPeakElement(int[] nums) {
        int len = nums.length;
        if (len == 1) return 0;
        int start = 0;
        int end = len -1;
        int res = 0;
        if (nums[start]>nums[start+1]) return 0; // according to nums[-1] = nums[n] = -∞, 
        if (nums[end]>nums[end-1]) return end;// so return start or end if one of them is greater than its neighbor.
        while (start<end) {  
            int mid = (start + end)/2;
            if (nums[mid]>nums[mid+1] && nums[mid]>nums[mid-1]) { //mid is greater than its neighbors
                res = mid;
                break;
            }else if (nums[mid]<nums[mid+1]) {
                start = mid;
            }else {
                end = mid;
            }
        }
        return res;
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32252次
    • 积分:1612
    • 等级:
    • 排名:千里之外
    • 原创:133篇
    • 转载:3篇
    • 译文:0篇
    • 评论:22条
    文章分类
    最新评论