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] = -∞.

    Example 1:

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

    Example 2:

    1. Input: nums = [1,2,1,3,5,6,4]
    2. Output: 1 or 5
    3. Explanation: Your function can return either index number 1 where the peak element is 2,
    4. or index number 5 where the peak element is 6.

    Note:

    Your solution should be in logarithmic complexity.


    题意

    给定一个整数数组,将所有整数按顺序连成一条折线图,要求找到其中任意一个极大值的下标(下标-1和n对应的值为负无穷)。解法的时间复杂度应为162. Find Peak Element (M) - 图1#card=math&code=O%28NlogN%29&height=20&width=77)。

    思路

    很明显是要使用二分法查找,问题只需要找到任意一个元素,使其比前后两个元素都大。


    代码实现

    1. class Solution {
    2. public int findPeakElement(int[] nums) {
    3. int left = 0, right = nums.length - 1;
    4. while (left < right) {
    5. int mid = left + (right - left) / 2;
    6. if (nums[mid] > nums[mid + 1]) {
    7. right = mid;
    8. } else {
    9. left = mid + 1;
    10. }
    11. }
    12. return left;
    13. }
    14. }