Find Peak Element-找出峰值元素w问题描述

  • 问题描述:

    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.  Note:Your solution should be in logarithmic complexity.

  • 问题解析: 最近老是看错题目的意思,峰值元素并不一定是整个数组中最大的。这道题最简单的方法当然是O(n)的遍历方法,可是既然是个Medium类型的题目,题目要求的复杂度是O(logn),一下子就将题目难度提了上来,很明显要利用二分搜索。我们知道二分搜索有几个key points。一是循环的终止条件,二是low和high指针的移动,只要不是连续的三个元素,我们就可以继续往下搜索,二分搜索每次的中间元素可以用来作为基准,如果nums[mid] < nums[mid-1],说明mid肯定无法作为peak,此时low = mid; 如果nums[mid] < nums[mid+1],mid也无法作为基准,但是此时应该high = mid。否则mid就是peak。此外,算法终止时,应该是移动到了某一段,此时判断low和high即可。代码如下:

  • public class Solution {
        public int findPeakElement(int[] nums) {
            if(nums.length == 1)
                return 0;
            int low = 0, high = nums.length -1, mid;
            while(low + 1 < high){
                mid = low + ((high - low) >> 1);
                if(nums[mid] < nums[mid-1])
                    high = mid;
                else if(nums[mid] < nums[mid + 1])
                    low = mid;
                else return mid;
            }
            return nums[low] > nums[high] ? low : high;
        }
    }


你可能感兴趣的:(Leetcode编程)