从零开始的蓝桥杯打怪升级 算法的时间复杂度和空间复杂度

6 阅读2分钟

算法-算法的时间复杂度和空间复杂度

算法的时间复杂度

时间复杂度描述的是算法执行时间随输入规模增长的变化趋势,它不计算算法实际运行的毫秒数,而是关注输入规模 n 增大时,操作次数的增长量级。

算法的空间复杂度

空间复杂度描述的是算法运行所需的额外空间随输入规模增长的变化趋势,同样关注增长量级,不计入输入数据本身占用的空间。

在python的实现方法

    import time
    import tracemalloc
    from typing import Callable, List

    class AlgorithemAnalyer():
        def __init__(self):
            self.compare_count = 0
            self.swap_count = 0

        def compare(self, a: int, b: int) -> int:
            self.compare_count += 1
            return a - b
        #     回归一个a - b值 通过判断大于零或者是小于零来进行处理

        def swap(self, arr: List, i: int, j: int):
            self.swap_count += 1
            arr[i] , arr[j] = arr[j] , arr[i]

        def time_it(self, func: Callable, *args, **kwargs) -> tuple:
            start_time = time.perf_counter()
            result = func(*args, **kwargs)
            end_time = time.perf_counter()
            return result, end_time - start_time
            # 计算时间复杂度

        def space_it(self, func: Callable, *args, **kwargs) -> tuple:
            tracemalloc.start()
            result = func(*args, **kwargs)
            current, peak = tracemalloc.get_traced_memory()
            tracemalloc.stop()
            return result, peak / 1024
            # 计算空间复杂度

        def reset(self):
            self.compare_count = 0
            self.swap_count = 0

细节详解

def time_it(self, func: Callable, *args, **kwargs) -> tuple:
    start_time = time.perf_counter()
    result = func(*args, **kwargs)
    end_time = time.perf_counter()
    return result, end_time - start_time
# 计算时间复杂度

通过 time_it(self, func: Callable, *args, **kwargs)接收算法的函数
*args,**kwargs来接受需要计算的算法的所有参数

    def space_it(self, func: Callable, *args, **kwargs) -> tuple:
        tracemalloc.start()
        result = func(*args, **kwargs)
        current, peak = tracemalloc.get_traced_memory()
        tracemalloc.stop()
        return result, peak / 1024

通过 space_it(self, func: Callable, *args, **kwargs)接收算法的函数
peak 几乎表示了空间复杂度

参考博文
[1]: 算法 - 十大经典排序算法(动图演示)十大经典排序算法 - 动图演示 - 实现代码 - 效果对比。 冒泡、选择、插入、归 - 掘金