蟒蛇。列表中的<remove element =“”>

时间:2016-07-08 13:26:54

标签: python-2.7

名称:

  

172. Remove Element

enter image description here 说明:

  

给定一个数组和一个值,删除所有出现的值并返回新的长度。

     

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

我的回答:

  

在LintCode上

A = [0,4,4,0,0,2,4,4]
elem = 4
def sss(A, elem):   
    if A == []:
        return A
    if elem in A:
        print A
        sortedA = sorted(A)
        print sortedA
        li = []
        for i in xrange(len(sortedA)):
#           print type(i)
            if sortedA[i] == elem:
                li += [i]
                print li
        newLength = sortedA[:min(li)] + sortedA[max(li)+1:]
        print newLength
        return newLength
    else:
        return A

print sss(A, elem)
  

在我的Mac上

{{1}}

这个答案我的Mac 工作正常,但 On LintCode 不接受。

2 个答案:

答案 0 :(得分:2)

为什么不使用列表推导来过滤掉不需要的元素?

php: {
    dist: {
        options: {
            keepalive: true,
            open: true,
            port: 5000
        }
    }
},

这里的关键是作业左侧的切片表示法。这使它成为“就地”操作,因此原始列表class Solution: def removeElement(self, A, elem): A[:] = [item for item in A if item != elem] return len(A) 被改变,而不是复制。

使用示例:

A

答案 1 :(得分:0)

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

方法I:如果元素不是 val (逻辑方法)

,则覆盖它们
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
   

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

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

方法III-方法2的改进形式(Python方式)

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

    

方法IV-Python方式

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

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

相关问题