Why my code is wrong?

  • 0
    public int removeElement(int[] A, int elem) {
    	int cnt = 0;
    	int[] tmp = new int[A.length];
    	for (int i = 0; i < A.length; i++) {
    		if (A[i] == elem) {
    		} else {
    			tmp[cnt++] = A[i];
    	A = Arrays.copyOf(tmp, cnt);
    	return A.length;

    The judge result is : wrong

  • 0

    use ++cnt instead of cnt++

  • 0

    You shouldn't use Arrays.copyOf() to try to change the origin A,and the numbers of A will not change if you do so.Just try to use the "for" loop to change the A's elements one by one,and the result will be correct.

Log in to reply

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