My java solution


  • 0
    public int removeElement(int[] nums, int val) {
        if(nums.length==1 && nums[0]!=val) return 1;
        else if(nums.length==1 && nums[0]==val) return 0;
        
        int leftPointer = 0, rightPointer = nums.length-1, count = 0;
        while(leftPointer<=rightPointer) {
            while(leftPointer<=rightPointer && nums[leftPointer]!=val) {
                leftPointer++;
            }
            while(leftPointer<=rightPointer && nums[rightPointer]==val) {
                rightPointer--;
                count++;
            }
            if(leftPointer<rightPointer) {
                int tmp = nums[leftPointer];
                nums[leftPointer] = nums[rightPointer];
                nums[rightPointer] = tmp;
            }
        }
        return nums.length-count;
    }

Log in to reply
 

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