[LeetCode][Python]27. Remove Ele

作者: bluescorpio | 来源:发表于2017-04-29 15:17 被阅读76次

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)

相关文章

网友评论

    本文标题:[LeetCode][Python]27. Remove Ele

    本文链接:https://www.haomeiwen.com/subject/cmvzzttx.html