Neat C++ Binary Search Solution


  • 0
    L
    class Solution {
    public:
        int findPeakElement(const vector<int> &num) {
            size_t n = num.size();
            if (n == 0) {
                return -1;
            }
            if (n == 1) {
                return 0;
            }
           
            if (num[0] > num[1]) {
                return 0;
            }
            if (num[n-1] > num[n-2]) {
                return n-1;
            }
    
            int low = 0, high = n-1;
            while (low <= high) {
                int mid = low + ((high - low) >> 1);
                int left = num[mid-1], right = num[mid+1];
                if (left < num[mid] && num[mid] > right) {
                    return mid;
                }
                else if (left < num[mid] && num[mid] < right) {
                    low = mid;
                }
                else {
                    high = mid;
                }
            }
            return -1;
        }
    };

  • 0
    G

    can this work on 3 3 3 3 3 3 4 3 3?


  • 0

    Instructions mention that adjacent elements are different.


  • 0
    J

    not work on [1, 7, 3, 4, 5, 6, 7]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.