O(n) Java Solution, very fast according to the judging system


  • 1
    J
    public int removeElement(int[] nums, int val) {
        if(nums.length == 0) return 0;
        if(nums.length == 1) return nums[0] == val ? 0 : 1;
        int i=0, j=nums.length-1;
        while(i <= j) {
            if(nums[j] == val) j--;
            else {
                if(nums[i] == val) {
                    nums[i] = nums[j];
                    j--;
                    i++;
                } else {
                    i++;
                }
            }
        }
        return i;
    }

  • 0
    E

    Hi! Today it is not so fast =). Submitted your code at least 5 times. Average time is about 300 ms that stands for average.


Log in to reply
 

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