C++ solution, 4ms, recursive


  • 0
    S
    class Solution {
    public:
        int findPeakElement(vector<int>& nums) {
            int n = nums.size();
            if(n == 0) {    return -1;  }
            else if(n == 1) {    return 0; }
            else if(n == 2) {   return nums[0] > nums[1] ? 0 : 1;   }
            else { // n >= 3
                if(nums[0] > nums[1]) { return 0;   }
                if(nums[n-1] > nums[n-2]) { return n-1; }
                return RecFind(nums, 1, n-2);
            }
        }
    private:
        int RecFind(const vector<int> &nums, int start, int end) {
            if(start == end) {  return end; }
            else if(start + 1 == end) {
                return nums[start] > nums[end] ? start : end;
            }
            else {
                int mid = (start + end) / 2;
                if(nums[mid] < nums[mid-1]) {
                    return RecFind(nums, start, mid);
                } else if(nums[mid] > nums[mid+1]) {
                    return mid;
                } else {
                    return RecFind(nums, mid, end);
                }
            }
        }
    };

Log in to reply
 

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