27. Remove Element

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.

把数组中等于val的值移除,然后返回数组长度。要求没有额外空间。

两个指针,一个从左往右,一个从右往左,如果左边的数等于value,和右边交换

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        r = len(nums) - 1
        l = 0
        while l <= r:
            if nums[l] == val:
                nums[l] = nums[r]
                r -= 1
            else:
                l += 1
        return l
原文地址:https://www.cnblogs.com/whatyouthink/p/13262825.html