首页 > 代码库 > LeetCode-Find Peak Element

LeetCode-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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

解题报告: 当时看着题就想用一个for一个个搜索,后面看到复杂度要log,又要用到二分搜索。

                  第一个要注意的就是num[0]与num[n-1],数组边界的问题,怎么判断。

                 使用num[middle-1],num[middle],num[middle+1],进行判断是什么情况。

                 搜索出来就四种情况:1,上升沿的时候,low = middle +1;

                                                    2,下降沿的时候,high=middle-1;

                                                    3,波峰,return middle;

                                                    4,波谷,high= middle -1;


class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        int n = num.size();
        int low = 0;
        int high = n - 1;
        if(n == 1) return 0;

        while(low <= high) {
            int middle = (low + high) / 2;
            if(middle ==  0) {
              if(num[middle] > num[middle + 1])
                 return middle;
                 else low= middle +1;
            }
            else if( middle == n - 1) {
                if(num[middle] > num[middle - 1])
                    return middle;
                    else high= middle -1;
            }
             else if( num[middle] > num[middle + 1] && num[middle] > num[middle - 1])
                     return middle;
                else if(num[middle - 1] > num[middle] && num[middle] > num[middle + 1])
                     high= middle -1;
                     else if(num[middle - 1] < num[middle] && num[middle] < num[middle + 1])
                       low= middle +1;
                       else high= middle -1;
        }
    }

};



LeetCode-Find Peak Element