时间复杂度-们

一些选择题,会给一小段代码,求时间复杂度。
或者有些代码写完,会要求分析时间复杂度。
这里写一些例子,以后遇到不断补充。

基本的

1 – Constant Time

look up table (hashtable)
如果是完美hash,则worst是O(1)
如果不是完美hash,则worst是O(n)
on average, O(1)

log (log N)

Shrinking by a Square Root

procedure A(n)
begin
	if (n < 3)
		return 1
	else 
		return A(ceiling(sqrt(n)))
	end
end

log N – Logarithmic Time

reduces the size of the input data in each step

  • operations on 二叉树Binary Tree
  • 二分搜索Binary Search
int a = 1;
while (a < n) {
	a = a * 2;
}

N – Linear Time

N * log N – Quasilinear Time

排序算法:

  • 归并排序merge sort
  • 快速排序quick sort
  • 堆排序heap sort
  • 希尔排序
void quicksort(int list[], int left, int right)
{
    int pivot = partition(list, left, right);
    quicksort(list, left, pivot - 1);
    quicksort(list, pivot + 1, right);
}

Amortized time per operation using a bounded priority queue (from wiki)

N2 – Quadratic Time

finding all subsets of a set: 0(2^n) —>n个元素,每个都可以”选“/”不选“,222*…*2 (共n个)

排序算法:

  • 冒泡排序Bubble sort
  • 插入排序Insert sort

2n – Exponential Time

growth doubles with each addition to the input data set

  • Find all subsets
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

N!

finding all permutations of a string: 0(n!) —>n个位置,第一个位置有n种选择,第二个位置n-1中,…,n*(n-1)(n-2)…21

  • the Heap’s algorithm, which is used for generating all possible permutations of n objects. 原文
def heap_permutation(data, n):
    if n == 1:
        print(data)
        return
    
    for i in range(n):
        heap_permutation(data, n - 1)
        if n % 2 == 0:
            data[i], data[n-1] = data[n-1], data[i]
        else:
            data[0], data[n-1] = data[n-1], data[0]
    
if __name__ == '__main__':
    data = [1, 2, 3]
    heap_permutation(data, len(data))
  • Travelling salesman problem

Big-O Cheat Sheet

下面的这两个图都是从这里A这里B 抄过来的:
在这里插入图片描述
在这里插入图片描述

graph

下图摘自这里
在这里插入图片描述

复合的

有些code snippet是两种函数交织在一起,互相传input/output。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值