C++ 6ms simple


  • 0
    class Solution {
    public:
        int findPeakElement(vector<int>& num) {
            if(num.empty()) return -1;
            if(num.size()==1) return 0;
            int left = 0;
            int right = num.size()-1;
            while(left < right-1) {
                int mid = (left+right)/2;
                if(num[mid]>num[mid+1] && num[mid]>num[mid-1]) return mid;
                else if(num[mid]<num[mid+1] && num[mid]<num[mid-1]) left = mid;
                else if(num[mid-1]<num[mid] && num[mid]<num[mid+1]) left = mid;
                else if(num[mid-1]>num[mid] && num[mid]>num[mid+1]) right = mid;
            }
            return num[left]>num[right]?left:right;
        }
    };
    

Log in to reply
 

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