Wrong Answer with input [2, 1, 2]. My code's output is 0.


  • 0
    N

    Hi, I don't know why the judge tell me my solution is wrong.

    Here is the code:

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

    The input of the judge is [2, 1, 2], and I return 0, as nums[0] > nums[-1] and nums[0] > nums[1].


  • 3

    Apparently you're messing up the judge by modifying its vector. If you restore the vector before you return or if you remove the & from the signature, it gets accepted.

    I guess since there's no single answer here, the judge can't just compare your output to the correct output but checks whether your output points to a peak, which it doesn't since you shifted the values.


  • 0
    N

    Wow you're right!


  • 0
    W

    Totally correct. Kind of silly and you would think they would mention that in the problem instructions. Thanks anyways though!


  • 0

    @wootencl Well I'd say a function called find... shouldn't modify anyway, and if it does, it should be clear that that's risky.


Log in to reply
 

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