My two Java solution #two-pointer #filling-good-numbers


  • 0

    The first solution comes into my mind is about using a left pointer to detect the first and bad number and a right pointer to detect the first good number. As long as the right pointer is valid, switch the content of what left and right pointers pointing to.

    public class Solution {
        public int removeElement(int[] nums, int val) {
            int l=0, r=0;
            while(r < nums.length) {
                while(l < nums.length && nums[l] != val) l++;
                r = l + 1;
                while(r < nums.length && nums[r] == val) r++;
                
                if (l < nums.length && r < nums.length) {
                    int tmp = nums[l];
                    nums[l] = nums[r];
                    nums[r] = tmp;
                }
            }
            
            return l;
        }
    }
    

    This works but not is an elegant solution. Especially we have to think about what should be returned at the end of the function, l or l+1, which is error probing.


    My second solution is to fill the front part of the array with good number. Instead of struggling with l and l+1, we have a clear count about the good number.

    public class Solution {
        public int removeElement(int[] nums, int val) {
            int count = 0;
            for (int num : nums) {
                if (num != val) {
                    nums[count++] = num;
                }
            }
            
            return count;
        }
    }
    

Log in to reply
 

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