循环排序的时间复杂度是 O(n^2)参考
但是,该解决方案声称以下涉及循环排序的算法仅使用 O(n)。时间复杂度不应该是 O(n^2) 吗?
def find_all_missing_numbers(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
i = 0
# This is cycle sort and should use O(n^2)?!
while i < len(nums):
j = nums[i] - 1
if nums[i] != nums[j]:
nums[i], nums[j] = nums[j], nums[i] # swap
else:
i += 1
missingNumbers = []
# O(n)
for i in range(len(nums)):
if nums[i] != i + 1:
missingNumbers.append(i + 1)
return missingNumbers
#
时间复杂度 = O(n^2 + n) = O(n^2)。解决方法错了吗?