Test input [4,5] 4, the expected output is [5]. Why!?


  • 2
    B

    The question is asking the new length so that should it be 1 for the new array length. Why the expected output is [5]?

    My former code

    if (A.length==0 || A==null){
    		return 0;
    	}
    	ArrayList<Integer> a=new ArrayList<Integer>();
    	for (int i=0;i<A.length;i++){
    		if (A[i]!=elem){
    			a.add(A[i]);
    		}
    	}
    	return a.size();
    

    And my accepted code

    if (A.length==0 || A==null){
    		return 0;
    	}
    	int count=0;
    	for (int i=0;i<A.length;i++){
    		if (A[i]!=elem){
    			A[count]=A[i];
    			count++;
    		}
    	}
    	return count;
    

    In my machine I tested input [4,5] 4. Both of them return 1 but online judge they are totally different. Why?


  • 1
    V

    Maybe the OJ checked the value of A , your former code leaves A behind and created a new list, while the accepted code covers the value of A.


Log in to reply
 

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