题目:给定一个数值nums和一个值val,原地移除所有数值等于val的元素,并返回移除后数组的新长度。
    (不要使用额外数组空间,你必须仅使用No.27 移除元素 - 图1额外空间并原地修改输入数组。)
    例:

    1. 给定 nums = [3,2,2,3], val = 3,
    2. 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2
    3. 你不需要考虑数组中超出新长度后面的元素。
    1. 给定 nums = [0,1,2,2,3,0,4,2], val = 2,
    2. 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4
    3. 注意这五个元素可为任意顺序。
    4. 你不需要考虑数组中超出新长度后面的元素。

    题解:
    一、双指针

    1. def removeElement(nums: List[int], val: int) -> int:
    2. if len(nums) == 0:
    3. return 0
    4. i = 0
    5. for j in range(len(nums)):
    6. if nums[j] != val:
    7. nums[i] = nums[j]
    8. i += 1
    9. else:
    10. continue
    11. return i
    12. 作者:qian-chen-yi-meng-k
    13. 链接:https://leetcode-cn.com/problems/remove-element/solution/shuang-zhi-zhen-fa-by-qian-chen-yi-meng-k/
    14. 来源:力扣(LeetCode
    15. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    知识点:
    快慢双指针
    通常可以用来原地改变数组:快指针用来遍历数组,慢指针根据快指针遍历的结果做出相应处理。

    class Solution:
        def removeElement(self, nums: List[int], val: int) -> int:
            if not nums:return 0
            slow = 0   
            n = len(nums)
            fast = n - 1
            while slow < fast:
                while slow < fast and nums[slow] != val:
                    slow += 1
                while slow < fast and nums[fast] == val:
                    fast -= 1
                nums[slow],nums[fast] = nums[fast],nums[slow]
                slow += 1
                fast -= 1
            res = 0
            #print(nums,slow,fast)
            #return fast + 1
            for i in range(n):
                if nums[i] == val:
                    return res
                res += 1
    
    作者:powcai
    链接:https://leetcode-cn.com/problems/remove-element/solution/yi-chu-yuan-su-by-powcai/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

    知识点:
    对撞双指针
    通常可以用来原地改变数组:正指针和反指针分别用来寻找不同的目标,最终实现换位或其它操作。

    二、python内置方法

    class Solution:
        def removeElement(self, nums: List[int], val: int) -> int:
            try:
                while True:
                    nums.remove(val)
            except:
                return len(nums)
    
    作者:xian-ren-mian
    链接:https://leetcode-cn.com/problems/remove-element/solution/-by-xian-ren-mian-2/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

    知识点:
    list.remove(a)
    从list中移除值为a的元素。

    class Solution:
        def removeElement(self, nums, val):
            for i in range(len(nums) - 1, -1, -1):
                if nums[i] == val:
                    nums.pop(i)
            return len(nums)
    
    作者:multiplierzhang
    链接:https://leetcode-cn.com/problems/remove-element/solution/27-yi-chu-yuan-su-by-multiplierzhang/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

    知识点:
    list.pop(a)
    从list中移除索引为a的元素。

    remove()和pop()的区别:

    x=[1,2,3,4,5,6]
    x.pop(5)
    x=[1, 2, 3, 4, 5]
    
    x=[1,2,3,4,5,6]
    x.remove(5)
    x=[1, 2, 3, 4, 6]