A weird Runtime Error, any help?


  • 0
    X

    leetcode told me:

    Runtime Error Message: Line 17: java.lang.ArrayIndexOutOfBoundsException: -1

    Last executed input: [1]

    Line 17 is if(num[mid] > num[mid-1] && num[mid] > num[mid+1])

    but it returns 0 when I run it in eclipse. I can't figure out why.

    public int findPeakElement(int[] num) {
        if(num.length <= 1)
            return 0;
        return search(num, 0, num.length-1);
    }
    
    private int search(int[] num, int low, int high)
    {
        int mid = (low+high)/2;
        if(low == high)
            return low;
        if(mid == 0 && num[0] > num[1])
            return 0;
        if(mid == num.length-1 && num[mid] > num[mid-1])
            return mid;
        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])
            return search(num, low, mid);
        else
            return search(num, mid, high);
    }

  • 0
    S

    what was your input for search method?
    if there are 2 elements in the array num, the mid would be 0, mid - 1 = -1, so it out of the bounds


  • 0
    X

    input is [1], I think the following code should be executed and return 0, so function search can not be called in this test case

    if(num.length <= 1)
    return 0;


  • 0
    S

    with 2 elements, num.length == 2


  • 0
    X

    thanks, I realized where I'm wrong


Log in to reply
 

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