Leetcode162-Find Peak Element

题目:

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.

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

Example2:
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.

思路:

本题有两种解法。首先自然是非常简单粗暴的一个一个找,并且比较两边的元素。找到一个符合条件的就break出循环。但是注意最后需要控制好边界。结果虽然过了但是整个算法跑的非常慢。

本题推荐使用第二种解法,也就是二分法来解决。首先找到中间元素设为mid,如果mid位置上的元素大于mid+1上的元素,则说明咱们要找的目标元素可能在左边,此时将right设为mid。反之,如果mid+1上的元素大于mid上的元素,则目标元素可能在右边,此时将left设为mid+1。最后返回位置left。

代码:

/**
     * Find peak element
     * @param nums
     * @return
     */
    public int findPeakElement(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int left = 0;
        int right = nums.length - 1;
        while(left < right){
            int mid = (left + right) / 2;
            if(nums[mid] < nums[mid + 1]){
                left = mid + 1;
            }else{
                right = mid;
            }
        }
        return left;
    }
    原文作者:BlueSkyBlue
    原文地址: https://www.jianshu.com/p/680762a27ff0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞