【问题标题】:Is this an O(N) solution? I'm being told this is O(N^2) because of the in keyword这是一个 O(N) 解决方案吗?我被告知这是 O(N^2) 因为 in 关键字
【发布时间】:2021-11-28 22:25:42
【问题描述】:
我相信下面的代码是一个 O(N) 解决方案,但我被告知它是 O(N^2),因为 in 关键字。这是真的吗?
代码:
class Solution:
def twoSum(self, nums, target):
for i,v in enumerate(nums):
value = target - v
if value in nums and nums.index(value)!= I:
return (nums.index(value),I)
break
【问题讨论】:
标签:
python
data-structures
array-algorithms
【解决方案1】:
x in a_list 和 nums.index(value) 一样是 O(n) ...所以你的内部 if 语句是 O(2n) 而你的外部 for 循环是 O(n)
所以你有 O(n)*O(2n) = O(2n^2) = O(n^2)
O(n)解如下
def twoSum(x,targetValue):
# pending values is a dict of index's mapped where the key is key + x[pendingValues[key]] = targetValue
pendingValues = {}
for i,value in enumerate(x):
if value in pendingValues: # in Dict is only O(1)
# this is a match return both matching index's
return (pendingValues[value],i)
else:
# not a match store the index as matchedTarget=index
pendingValues[targetValue-value] = i