Why my code is wrong?


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

    The judge result is : wrong


  • 0
    R

    use ++cnt instead of cnt++


  • 0
    G

    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.