gpt4 book ai didi

python - 以下解决方案的时间复杂度是 O(N) 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:12:30 25 4
gpt4 key购买 nike

我尝试计算函数“twoSum”的时间复杂度,并写下每行的成本及其执行次数。最后,我制作了两个向量:一个用于成本,另一个用于频率,然后计算它们的内积。我得到以下内容: (n + n + nlogn + n + n + nlogn + n + n + n + n) = 9n + 2logn >> 9n 占主导地位,所以时间复杂度是 O (n)。如果我错了请纠正我!

class Solution(object):

def binarySearch(self,arr, l, r, x):
if r >= l:
mid = l + (r - l)/2
if arr[mid] == x: return mid
elif arr[mid] > x:return self.binarySearch(arr, l, mid-1, x)
else: return self.binarySearch(arr, mid + 1, r, x)
else:return -1

def twoSum(self, nums, target):
temp = [i for i in nums] # o(n) 1 time
nums = list(set(nums)) # o(n) 1 time
nums.sort() # o(nlogn) 1 time
for i in range(len(nums)): # o(n) 1 time
s = target - nums[i] # o(1) n times
idx_binary = self.binarySearch(nums, 0, len(nums)-1, s) # o(logn) > n times
if idx_binary > -1: # o(1) n times
idx = temp.index(s, temp.index(nums[i])+1) # o(n) > 1 time
return [temp.index(nums[i]), idx] # o(n) > 1 time
else:
return [temp.index(nums[i]), temp.index(s)] # o(n) > 1 time

最佳答案

你的化简有误,应该是9n + 2nlogn 其中nlogn占主导地位,所以答案是O(nlogn)

关于python - 以下解决方案的时间复杂度是 O(N) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com