Why I got run time error when do B[A[i]]++;


  • 0
    X

    public class Solution {
    public int singleNumber(int[] A) {
    int[] B;
    int i,max,n;
    max = 0;
    n = 0;
    for (i=0;i<A.length;i++)
    {
    if (max<A[i])
    max = A[i];
    }
    B=new int[max+1];
    for (i=0;i<B.length;i++)
    B[i]=0;
    for (i=0;i<A.length;i++)
    B[A[i]]++;
    for (i=0;i<B.length;i++)
    if (B[i]==1)
    {
    n=B[i];
    break;
    }
    return n;
    }
    }


  • 0
    M

    Formatting your code makes it easier to understand your algorithm. You should also offer what input gave the runtime error, and provide which runtime error it was.

    As it is, your runtime error is most likely indexOutOfBounds, occurring when a number in A is negative. These are not unsigned integers, so you cannot guarantee that they will all fit inside 0-max. Attempting to use a negative index will, of course, not be in the range 0-(array.length-1), so will be out of bounds.

    If you are inexplicably tied to this solution, you need to find the minimum number as well, and use A[i]-min as your index.

    Also, if the maximum number is negative, your algorithm will crash at B=new int[max+1]. To avoid this, instead of starting at max = 0, start at max = A[0].


Log in to reply
 

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