My simple C++ logn solution


  • 4
    Z

    Since nums[-1] = nums[n] = INT_MIN, a valid solution is guaranteed to exist.

    class Solution {
    public:
        int findPeakElement(vector<int>& nums) {
            int l = 0, r = nums.size();
            while (l+1 < r) {
                int m = (l+r)/2;
                if (m && nums[m] < nums[m-1])
                    r = m;
                else
                    l = m;
            }
            return l;
        }
    };

  • 0
    S

    Not sure why everyone uses the same algorithm as this one. the task says you may have multiple peaks which means you may miss the biggest peak while you cut the range by middle.
    did you try the test when the input is: 1 2 4 8 4 3 100 1. I bet your code will return 3 instead of 6 cause it will miss it in a first iteration.


  • 0
    L

    The question said that " The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. "

    That is why i do not think this question is good.


  • 0
    H

    if the input is 5 4 3 2 2 2 2 2 2 2, your code will return 9, but the answer is 0.


  • 0
    H

    sorry, I have seen the problem constraint: num[i] ≠ num[i+1]


Log in to reply
 

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