27. Remove Element

# Easy

Exchange element = val with the last element of the list, and pop the last element out.

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        while i < len(nums):
            if nums[i] == val:
                temp = nums[i]
                nums[i] = nums[-1]
                nums[-1] = temp
                nums.pop()
            if i < len(nums) and nums[i] != val:
                i += 1

        return len(nums)

Last updated