Simple Java solution


  • 3
    J
    public int removeElement(int[] nums, int val) {
        int i=0;
        int j=0;
        for(j=0; j<nums.length;j++){
            if(nums[j]!=val){
                nums[i]=nums[j];
                i++;
            }
        }
        return nums.length-j+i;
    }

  • 1
    E

    It is obviously that (nums.length - j == 0), why not just return i?


  • 0
    J

    Because the value of i may change. Plz consider the following case: input{[3,2,2,2,3], 2}. Moreover, j-i is the number of elements deleted.


  • 0
    A

    nums.length - j = 0. Just return i. The value of i may change, but the value of j by the end of the for loop will ALWAYS equal nums.length.


  • 0
    M

    This solution keeps the original order in the array, and could be an extending problem for this question during interview.


  • 0
    C

    If the input is [0] 2, then j = 0, and nums.length - j = 1.


Log in to reply
 

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