[英]Why time complexity of following algorithm(cycle sort?!) is O(n)?
循环排序的时间复杂度是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)。 解决方案错了吗?
这不是循环排序,如果数组由范围[1, len(array)]
的数字组成,则该算法旨在查找缺少的数字。
print(find_all_missing_numbers([5,4,3,2,1]))
print(find_all_missing_numbers([1,2,3,5,5]))
print(find_all_missing_numbers([2]))
[]
[4]
错误
该行假设存储的数字给出了正确的位置,仅当数字在上面所示的范围内时才有效。
j = nums[i] - 1
循环排序花费线性时间为每个数字寻找合适的位置。
def find_all_missing_numbers(nums):
i = 0 # Will happen only once so O(1)
# no linear search for true position
while i < len(nums):
j = nums[i] - 1 # Will happen once per each iteration
if nums[i] != nums[j]: # Condition Check Will happen once per iteration
nums[i], nums[j] = nums[j], nums[i] # Will happen if if Condition is true so "c" times
else:
i += 1 # Will happen if if Condition is not true so "c'" times
missingNumbers = []
# O(n)
for i in range(len(nums)):
if nums[i] != i + 1:
missingNumbers.append(i + 1)
return missingNumbers
所以:
1 + Len(nums)*(1 + 1 + c + c' + 1) + n
如果Len(nums)= n那么
1 + 3n + (c + c')n + n = 1 + (3+C)n + n ~ O(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.