降低运行时复杂度!减少Python中的嵌套循环

时间:2020-04-17 15:59:58

标签: python python-3.x list algorithm loops

我正在研究提供/接受标准输入/输出的python程序。第一行给出测试用例的数量 T 。第二行给出数据的大小 N 。第三行和第四行分别给出长度为 N 以空格分隔的整数。该程序将Set A B 排列为Set A 的最大项目数大于其均等索引 B 中的em>项目。下面是我的代码:

 def main():
   T=int(input())
   for ii in range(T):
        N=int(input())
        revo=list(map(int, input().split()))
        star=list(map(int, input().split()))
        win=0
        for i in range(N):
            a=1
            for j in range(revo[i]):
                b=revo[i]-a
                if b in star:
                    win=win+1
                    t=star.remove(b)
                    break
                a=a+1
        print(win)
main()

输入为:

1
10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6

输出为 7 ,因为在进行最佳排列时,集合A的项比集合B中的项大7。但是当我们输入大型数据集时,产生输出要花费很长时间。有什么更好的功能可以用来减少运行时间?

1 个答案:

答案 0 :(得分:1)

您的解决方案是O(k*n^2),确实很多。

 def main():
   T=int(input())
   for ii in range(T): # ignoring number of inputs in time complexity
        N=int(input())
        revo=list(map(int, input().split())) # O(n), doesn't matter
        star=list(map(int, input().split())) # O(n), doesn't matter
        win=0
        for i in range(N): # n
            a=1
            for j in range(revo[i]): # n*k, k depends on 
                                     # how big is each number, hard to tell
                b=revo[i]-a
                if b in star: # k*n^2
                    win=win+1
                    t=star.remove(b) # normally this would multiply by n, but
                                     # remove can be called at most n times 
                    break
                a=a+1
        print(win)
main()

如果您先对两个列表进行排序,则可以将袍子降低到O(nlogn)。这是我的解决方案:

def solve(list1, list2):
    list1 = sorted(list1) # n*logn
    list2 = sorted(list2) # 2*n*logn
    pos_in_list1, pos_in_list2 = 0, 0
    while pos_in_list1 < len(list1): # 2*n*logn + n
        if list1[pos_in_list1] > list2[pos_in_list2]:
            pos_in_list1 += 1
            pos_in_list2 += 1
        else:
            pos_in_list1 += 1
    return pos_in_list2


print(solve([3, 6, 7, 5, 3, 5, 6, 2, 9, 1], [2, 7, 0, 9, 3, 6, 0, 6, 2, 6]))
# 7


def main():
    _ = input()  # we don't need n
    list1 = [int(i) for i in input().split()] # O(n), doesn't matter
    list2 = [int(i) for i in input().split()] # O(n), doesn't matter
    print(solve(list1, list2))

O(2*n*logn + n) = O(nlogn)