Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example: Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

Hint:

  1. Try two pointers.
  2. Did you user the property of "the order of elements can be changed"?
  3. What happens when the elements to remove are rare?
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        nums.sort()
        pos = []
        for i in range(len(nums)):
            if nums[i] == val:
                pos += i,
        if not pos:
            return len(nums)
        elif len(pos) == 1:
            nums[:] = nums[0:pos[0]] + nums[pos[0]+1:]
        else:
            nums[:] = nums[0:pos[0]] + nums[pos[-1]+1:]
        return len(nums)

Trick 1:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        while val in nums:
            nums.remove(val)
        return len(nums)

Trick 2:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        nums[:] = [n for n in nums if n != val]
        return len(nums)

results matching ""

    No results matching ""