【问题标题】:Is there a way to make my function run faster?有没有办法让我的功能运行得更快?
【发布时间】:2022-10-04 17:26:19
【问题描述】:

我有这个功能,它的任务是找出多少个数字,可以从列表中以这样的方式选择,任何两个选择的数字之间的差不大于 t。我怎样才能使它的时间复杂度为 O(nlogn)?

def find_numbers(num_list, t):
    sorted_list=sorted(num_list)
    counter=0
    k=0
    n=0
    for i in range(len(sorted_list)):
        for j in range(k, len(sorted_list)):
            if sorted_list[j]-sorted_list[k]<=t:
                counter+=1
            else:
                break
        k+=1
    
        if counter>n:
            n=counter
        counter=0
    return n 

它应该如何工作的一些例子

print(find_numbers([2, 7, 14, 11, 7, 15], 11)) # 5
print(find_numbers([4, 2, 7, 1], 0)) # 1
print(find_numbers([7, 3, 1, 5, 2], 2)) # 3

在第三个例子中,可以从列表[7,3,1,5,2]中选择三个数字:3、1和2,并且这些数字之间的差异最多为2。

【问题讨论】:

  • 改掉使用for index in range(len(list)): 的习惯。使用for item in list:for index, item in enumerate(list):

标签: python performance


【解决方案1】:

您的总体设计是对列表进行排序,然后扫描以查看由不超过t 分隔的最长数字是什么。

但是,如果您意识到每次增加 i 时不需要重置 j,您的扫描效率会更高。在tsorted_list[i] 内直到sorted_list[j] 的所有数字也将在sorted_list[i+1] 的范围内,因为后者更大。这意味着扫描可以是O(n) 而不是O(n**2)

def find_numbers(num_list, t):
    sorted_list=sorted(num_list)
    n = 0
    j = 1  # j points to the first index that might be larger by more than t
    for i in range(len(sorted_list)):
        while j < len(sorted_list) and sorted_list[j] - sorted_list[i] < t:
            j += 1
        if j - i > n:  # no need to manually count, the indexes can do that for us
            n = j - i
    return n

可能有一种更优雅的编码方式,但这个版本解决了您所询问的复杂性问题。

【讨论】:

    【解决方案2】:

    你可以用zip

    def find_numbers(num_list, t):
        return return len([i for i in zip(num_list, num_list[1:]) if i[0]-i[1] <= t])
    

    执行:

    In [1]: print(find_numbers([2, 7, 14, 11, 7, 15], 11))
    5
    
    In [2]: print(find_numbers([4, 2, 7, 1], 0))
    1
    
    In [3]: print(find_numbers([7, 3, 1, 5, 2], 2))
    2
    

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2020-07-29
      • 1970-01-01
      • 2022-11-19
      • 2017-03-26
      • 1970-01-01
      • 2022-11-03
      • 2012-10-07
      • 1970-01-01
      相关资源
      最近更新 更多