Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是以下解决方案';时间复杂度O(N)?_Python_Algorithm_Time_Big O_Complexity Theory - Fatal编程技术网

Python 是以下解决方案';时间复杂度O(N)?

Python 是以下解决方案';时间复杂度O(N)?,python,algorithm,time,big-o,complexity-theory,Python,Algorithm,Time,Big O,Complexity Theory,我试图计算函数“twoSum”的时间复杂度,并写下每一行的开销以及它的执行次数。最后,我做了两个向量:一个是成本向量,另一个是频率向量,然后计算它们的内积。我得到如下结果:(n+n+nlogn+n+n+nlogn+n+n)=9n+2logn>>9n占主导地位,因此时间复杂度是O(n)。如果我错了,请纠正我 class Solution(object): def binarySearch(self,arr, l, r, x): if r >= l: mi

我试图计算函数“twoSum”的时间复杂度,并写下每一行的开销以及它的执行次数。最后,我做了两个向量:一个是成本向量,另一个是频率向量,然后计算它们的内积。我得到如下结果:
(n+n+nlogn+n+n+nlogn+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)

如果我理解正确,运行“O(logn)>n次”的行的时间复杂度为O(nlogn)