小编All*_*len的帖子

Python list.pop(i) 时间复杂度?

我在网上查了一下,知道它的list.pop()时间复杂度为 O(1),但时间复杂度list.pop(i)为 O(n)。在我编写 leetcode 时,很多人pop(i)在 for 循环中使用,他们说它的时间复杂度为 O(n),实际上它比我的代码快,我的代码只使用一个循环,但该循环中有很多行。我想知道为什么会发生这种情况,我应该使用pop(i)而不是多行来避免它吗?

示例:Leetcode 26. 从排序数组中删除重复项

我的代码:(比 75% 快)

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left, right = 0, 0
        count = 1
        while right < len(nums)-1:
            if nums[right] == nums[right+1]:
                right += 1
            else:
                nums[left+1]=nums[right+1]
                left += 1
                right += 1
                count += 1
        return count
Run Code Online (Sandbox Code Playgroud)

和其他人的代码,比 90% 快:(这家伙不说 O(n),但为什么 O(n^2) 比我的 O(n) 快?)

https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/477370/python-3%3A-straight-forward-6-lines-solution-90-faster-100-less-memory

我的优化代码(比 89% 快)

class Solution(object): …
Run Code Online (Sandbox Code Playgroud)

python algorithm time-complexity

5
推荐指数
1
解决办法
290
查看次数

标签 统计

algorithm ×1

python ×1

time-complexity ×1