Is this function O(N+M) or O(N*M)?

自闭症网瘾萝莉.ら 提交于 2019-12-10 15:34:40

问题


def solution(M, A):
    result = [0] * M
    maxCount = 0
    setAll = 0

    for i in range(0,len(A)):
        if (A[i] == M + 1):
            setAll += maxCount
            maxCount = 0
            result = [0] * M
        else:
            result[A[i] - 1] += 1

            if (result[A[i] - 1] > maxCount):
                maxCount = result[A[i] - 1]

    for j in range(0,len(result)):
        result[j] += setAll

    return result


A = [ 1, 1, 1, 1, 2, 3] 
M = 2

print solution(M, A) # result = [ 4, 4 ]


A = [ 1, 2, 2, 4, 1, 1] 
M = 3

print solution(M, A) # result = [ 4, 2, 2 ]

By my count, solution() loops through A N times and then loops result M times thus N+M. However, an online test said that it was instead N*M, leaving me stumped.


回答1:


It is O(M + N); there are no nested loops here. This can be reduced to the cost for the larger number; asymptotically, the smaller loop is not going to matter, making it O(N).

First you loop over A elements (N iterations), then separately you loop over M elements.




回答2:


It is O(N), because the there are N + M loops for a given input N, M. That reduces to the larger of the two (let's say that is N) for the purposes of time complexity, because we only take the most significant term. It would be O(N*M) if the second loop was nested inside the first.



来源:https://stackoverflow.com/questions/19879739/is-this-function-onm-or-onm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!