Remove Element

Problem: Remove Element

We can use two pointers to split the array into 3 parts: elements equal to target, elements not equal to target and non-dealt-with elements.

Code in Python:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        j = 0
        for i in xrange(len(nums)):
            if nums[i] == val:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1
        nums[:] = nums[j:]
        return len(nums)

Code in Java:

public class Solution {
    public int removeElement(int[] nums, int val) {
        int n = nums.length;
        int res = n;

        if (n == 0) return 0;
        if (n == 1) {
            if (nums[0] == val) return 0;
            return 1;
        }

        int i = 0, j = 0;
        while (j < n) {
            if (nums[j] == val) {
                res--;
                j++;
            } else {
                nums[i] = nums[j];
                i++;
                j++;
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""