[LeetCode][Python]27. Remove Element

Given an array and a value, 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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

思路:

  1. 使用[:]操作符得到list的copy,遍历list中的元素,如果和target相等,则从原list中删除。此处不能用index来检查,因为在处理过程中会把元素删除,有些元素下标变了,会被漏掉。
    def removeElement2(self, nums, val):
        for ele in nums[:]:
            if ele == val:
                nums.remove(val)
        return len(nums)

    原文作者:bluescorpio
    原文地址: https://www.jianshu.com/p/d447f935a83d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞