Why my code cannot pass OJ?


  • -1
    J
    Public class removeelements {
    public int removeElement(int[] nums, int val) {
    	ArrayList nums1= new ArrayList<Integer>();
    	 	for (int i=0; i<nums.length; i++){
    		nums1.add(nums[i]);
        }
    	int index =nums1.indexOf(val);
    	while (index>=0){
    		nums1.remove(index);
    		index = nums1.indexOf(val);
    	}
    	      return nums1.size();  
        }
    

    I thought my code is correct, but OJ said:

    Status: Wrong Answer
    Submitted: 6 minutes ago
    Input:
    [4,5], 4
    Output:
    [4]
    Expected:
    [5]
    

    I ran this code on my computer, the result is [5]not [4];Thanks for your help.


  • 0
    V

    Your code doesn't remove the elements in place. It removes elements from an ArrayList copy of the original array. You need to remove the elements from the nums array.


Log in to reply
 

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