Remove Element

题目描述

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

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

解题方法

因为不需要保持原有array的顺序等,所以遇到要去掉的就将末尾的换过了,并且用一个variable记录去掉的数的数量。

Solution

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if not nums:
            return 0
        numVal = 0
        length = len(nums)
        p = 0
        while p < length - numVal:
            if nums[p] == val:
                nums[p] = nums[length - 1 - numVal]
                numVal += 1
                #don't increment i here, cause you don't the new value
            else:
                p += 1

        return length - numVal

Reference