027 Remove Element

Original Description: Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

  • 要求:

  • 返回: 除去元素后的数组长度

  • 例子:
    • input: nums = [3,2,2,3], val= 3
    • output: 2



class Solution:
    def removeElement(self, nums, val):
        :type nums: List[int]
        :type val: int
        :rtype: int
        # swap numbers that equal to val into the end of the array
        j = len(nums)-1
        for i in range(len(nums) - 1, -1, -1):
            if nums[i] == val:
                nums[i], nums[j] = nums[j], nums[i]
                j -= 1
        return j+1