monocy

导航

手把手带你刷力扣(1)-时间复杂度和空间复杂度

 时间复杂度:算法的执行效率、算法的执行时间和输入值的关系

需要关注的是算法中的for循环和while循环,如均没有,时间复杂度为O(1)。

下面是常见时间复杂度的简单案例:

O(1):

def O1(num):
     i = num
     j = num * 2
     return i + j

O(logN):

def OlogN(num):
    i = 1
    while (i < num):
        i = i * 2
    return i

O(N):

def ON(num):
    total = 0
    for i in range(num):
        total += i
    return total

O(M+N):

def OMN(num1,num2):
    toal = 0;
    for i in range(num1):
        total += i
    for j in range(num2):
        total += j
    return total

O(NlogN):

def ONLogN(num):
    total = 0
    j = 1
    for i in range(num):
        while(j < num):
            total += i + j
            j =j * 2
    return total

O(N2):

def ON2(num):
    total = 0
    for i in range(num):
        for j in range(num):
            total += i + j
    return total

对比:

O(1) < O(logN)(二分查找) < O(N) < O(NlogN) (排序)< O(N2) < O(2N) < O(N!) 

 

空间复杂度:算法存储空间与输入值之间的关系

简单案例:

O(1):

def test1(num):
    total = 0
    for i in range(num):
        total += i
    return total

O(N):

def test2(num):
    array = []
    for num in nums:
        array.append(num)
    return array

对比:

O(1) < O(N) <  O(N2)

 

posted on 2022-04-29 10:44  Monocy219  阅读(120)  评论(0编辑  收藏  举报