简体   繁体   English

弹出一个元素并将相同元素附加到 Python 列表的时间复杂度是多少?

[英]What is the time complexity of popping an element and appending the same element to a Python list?

So I know popping an element from an an array is O(n) since you have to shift all the elements over by one.所以我知道从数组中弹出一个元素是 O(n) 因为你必须将所有元素移一个。 BUT, what if you popped an element AND appended that same element to the back of the array, all in one line.但是,如果您弹出一个元素并将相同的元素附加到数组的后面,所有这些都在一行中。 Would this be constant operation O(1) since you don't have to shift anything?这会是恒定的操作 O(1),因为您不必移动任何东西吗? Please see my code below with the comment.请在下面的评论中查看我的代码。

def moveZeroes(self, nums: List[int]) -> None:
        index = 0
        zeroes = nums.count(0)
        counter = 0
        while True:
            if counter == zeroes:
                break
            if nums[index] == 0:
                nums.append(nums.pop(index))  # THIS LINE RIGHT HERE
                counter += 1
            else:
                index += 1
  1. When you pop any element using its index, you make at most len(array) shifts to reduce the length by 1.当您使用其索引弹出任何元素时,您最多会进行 len(array) 移位以将长度减少 1。

  2. You can append an element into an array in O(1) time complexity.您可以在 O(1) 时间复杂度内将 append 一个元素放入一个数组中。

However, when you call nums.append(nums.pop(index)) .但是,当您调用nums.append(nums.pop(index))时。 It will first do step 1 and then do step 2. So overall, you still do O(n) operations.它将首先执行第 1 步,然后执行第 2 步。所以总的来说,您仍然执行 O(n) 操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM