Python 2.7 蟒蛇&书信电报;移除元件>;列表中

Python 2.7 蟒蛇&书信电报;移除元件>;列表中,python-2.7,Python 2.7,标题: 说明: 给定一个数组和一个值,删除该值的所有匹配项并返回新长度 元素的顺序可以更改,新长度之后的元素无关紧要 我的答覆是: 在代码上 在我的mac电脑上 这个答案在我的mac电脑上是好的,但在LintCode上是不行的。为什么不使用列表理解来过滤掉不需要的元素呢 class Solution: def removeElement(self, A, elem): A[:] = [item for item in A if item != elem]

标题:

说明:

给定一个数组和一个值,删除该值的所有匹配项并返回新长度

元素的顺序可以更改,新长度之后的元素无关紧要

我的答覆是:

在代码上

在我的mac电脑上


这个答案在我的mac电脑上是好的,但在LintCode上是不行的。

为什么不使用列表理解来过滤掉不需要的元素呢

class Solution:
    def removeElement(self, A, elem):
        A[:] = [item for item in A if item != elem]
        return len(A)
这里的关键是赋值左边的切片表示法。这使得它成为一个“就地”操作,因此原始列表
A
会发生变化,而不是复制

用法示例:

>>> l = [1, 2, 3, 4, 4, 5, 4, 10, 11, 4]
>>> len(l)
10
>>> Solution().removeElement(l, 4)
6
>>> l
[1, 2, 3, 5, 10, 11]
>>> len(l)
6

为什么不使用列表理解来过滤掉不需要的元素呢

class Solution:
    def removeElement(self, A, elem):
        A[:] = [item for item in A if item != elem]
        return len(A)
这里的关键是赋值左边的切片表示法。这使得它成为一个“就地”操作,因此原始列表
A
会发生变化,而不是复制

用法示例:

>>> l = [1, 2, 3, 4, 4, 5, 4, 10, 11, 4]
>>> len(l)
10
>>> Solution().removeElement(l, 4)
6
>>> l
[1, 2, 3, 5, 10, 11]
>>> len(l)
6

虽然这是一篇老文章,但我想添加我尝试过的不同方法。在所有情况下,时间复杂度都是O(n)

方法一:如果元素不是val(逻辑方法),则覆盖它们。

方法二:用最后一个数组元素覆盖val(逻辑方法)


它们的平均运行时间约为36毫秒,内存利用率约为13.8MB。

虽然这是一篇老文章,但我想添加我尝试过的不同方法。在所有情况下,时间复杂度都是O(n)

方法一:如果元素不是val(逻辑方法),则覆盖它们。

方法二:用最后一个数组元素覆盖val(逻辑方法)


它们的平均运行时间约为36毫秒,内存利用率约为13.8MB。

我将您的LintCode片段粘贴到LintCode中,“Lint”没有出现错误。啊,没关系。需要按提交。我知道问题是什么。将该值的所有引用移除到位;您正在使用sorted()创建列表的副本。你的解决方案太复杂了。@Fiskie它说元素的顺序可以更改,所以…and sorted()会构建一个全新的列表,因为它不会改变原始列表。我将你的LintCode片段粘贴到LintCode中,“Lint”没有给出错误。啊,别担心。需要按提交。我知道问题是什么。将该值的所有引用移除到位;您正在使用sorted()创建列表的副本。你的解决方案太复杂了。@Fiskie它说元素的顺序可以改变,所以…and sorted()会构建一个全新的列表,因为它不会改变原始列表。这个解决方案比我的更像pythonic。这个解决方案比我的更像pythonic。
def removeElement(self, nums: List[int], val: int) -> int:
   
    i : int = 0        # This will be an index pointer & will provide the sixe at the end
    
    for j in range(len(nums)):
        if nums[j] != val:       # if the values are not same         
            nums[i] = nums[j]    # Override the value at location i 
            i+=1
            
    return i
   
def removeElement(self, nums: List[int], val: int) -> int:
    i: int = 0
    n: int = len(nums)
    
    while(i<n):
        if(nums[i] == val):
            # Replace the element with last array element & reduce the array size by 1
            nums[i] = nums[n-1]
            n -=1
        else:
            i +=1
        
    return n
def removeElement(self, nums: List[int], val: int) -> int:
    i : int = 0
    n : int = len(nums)
        
    while i< n :
        print(i, nums, n)
        if val in nums[:n]:
            i = nums.index(val,0,n)
            nums[i] = nums[n-1]
            n -=1
        else:                 
            break
                    
    return n

    
def removeElement(self, nums: List[int], val: int) -> int:
    nums[:] = [x for x in nums if x !=val]
    
    return len(nums)