Expected output on input [1] is 0 ?


  • 0
    R

    My understanding is if input is [1] (equivalent to [-infinity, 1, -infinity] ) then the peak will be 1. However, OJ is failing with expected output as 0. Looks like I am missing something basic here ? Or something not right with this OJ test?

    Submission Result: Wrong Answer

    Input:
    [1]
    Output:
    1
    Expected:
    0

    EDIT: Appending my solution to the problem

    public class Solution {
        public int findPeakElement(int[] nums) {
    
            if (nums == null || nums.length == 0) return Integer.MIN_VALUE;
    
           int[] numsX = new int[nums.length+2];
            
            numsX[0] = Integer.MIN_VALUE;
            
            numsX[numsX.length-1] = Integer.MIN_VALUE;
            
            for (int i = 0; i < nums.length; i++)
                numsX[i+1] = nums[i];    
            
            return findPeakElemHelper(numsX, 0, numsX.length - 1);
        }
    
        private int findPeakElemHelper(int[] nums, int start, int end) {
    
            int midIndex = start + (end - start) / 2;
    
            int leftIndex = midIndex - 1;
        
            int rightIndex = midIndex + 1;
    
            int midVal = nums[midIndex];
            
            if (leftIndex < 0) return nums[1];
            
            if (rightIndex >= nums.length) return nums[nums.length - 2];
             
            int leftVal = /*(leftIndex < 0) ? Integer.MIN_VALUE :*/ nums[leftIndex];
        
            int rightVal = /*(rightIndex >= nums.length) ? Integer.MIN_VALUE :*/ nums[rightIndex];
    
            if (midVal >= leftVal && midVal >= rightVal) return midIndex;
    
            if (midVal <= rightVal) return findPeakElemHelper(nums, rightIndex, end);
    
            return findPeakElemHelper(nums, start, leftIndex);
        }
    }

  • 1
    R

    here is my Simple solution . I hope it will help .
    (Java language)

     public int findPeakElement(int[] nums) {
        if(nums == null || nums.length == 0)
        return 0;
        if(nums.length == 1 || nums[0] > nums[1])
        return 0;
        int n = nums.length;
        if(nums[n-1] > nums[n-2])
        return n-1;
        
        for(int i = 1; i < n-1; i++){
            if(nums[i] > nums[i-1] && nums[i] > nums[i+1])
                return i;
        }
        
        return 0;
    }

  • 0
    R
    if(nums.length == 1 || nums[0] > nums[1])
    return 0;
    

    For input [5, 2], the above code will return 0. Shouldn't it return 5 instead?


  • 0
    R

    Actually , In this problem they are interested in the index of the peak_eleneb.

    Therefore [5,2] will return 0 index of value 5.

    I hope its clear now.


  • 0
    R

    Thanks! yes, I was returning the value instead, which was wrong.


Log in to reply
 

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