Simple two pointers solution in Java, 14ms


  • 1
    M

    Two pointers technique; returns the number of "good" ints found.

    public class Solution {
        public int removeElement(int[] nums, int badNum) {
            if (nums.length == 0) {
                return 0;
            }
            int goodNums = 0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != badNum) {
                    swap(nums, i, goodNums);
                    goodNums++;
                }
            }
            return goodNums;
        }
        
        private void swap(int[] nums, int a, int b) {
            int temp = nums[a];
            nums[a] = nums[b];
            nums[b] = temp;
        }
    }
    

  • 0
    X

    You can also swap bad nums and array tail, descreasing tail index each time. I think in most cases these will require lesser operations. Even not swap - just replace bad num with an element from array tail. Like this:

    public int removeElement(int[] nums, int val) {
        int length = nums.length;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] == val) {
                nums[i] = nums[--length];
            }
        }
        return length;
    }

Log in to reply
 

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