数据结构与算法基础篇-复杂度

60 阅读1分钟

时间复杂度

估算程序指令的执行次数(执行时间)

空间复杂度

估算所需占用的存储空间

大O表示发(Big O)

一般用大O表示法来描述复杂度,它表示的是数据规模n对应的复杂度

忽略常数、系数、低阶

  • 9 >> O(1)
  • 2n + 3 >> O(n)
  • n² + 2n + 6 >> O(n²)
  • 4n³ + 3n² + 22n + 100 >> O(n³)

大O表示法仅仅是一种粗略的分析模型,是一种估算,能帮助我们短时间内了解一个算法的执行效率。

对数阶的细节

image.png

常见的复杂度

image.png

例子

普通列子

O(1)

public static void test1(int n) {
    // 执行1次
    if (n > 10) {
        System.out.println(n);
    } else if (n > 5) {
        System.out.println(n);
    } else  {
        System.out.println(n);
    }

    // int i = 0; 1次
    // i < 20; 20次
    // i++ 20次
    // System.out.println(i); 20次
    // 1 + 20 + 20 + 20
    for (int i = 0; i < 20; i++) {
        System.out.println(i);
    }

    // 62次
    // O(1)
}

O(n)

public static void test2(int n) {
    for (int i = 0; i < n; i++) {
        System.out.println(n);
    }
    // int i = 0; 1次
    // i < n; n次
    // i++ n次
    //  System.out.println(n); n次

    // 3n + 1
    // O(n)
}

O(n^2)

public static void test3(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            System.out.println(i + j);
        }
    }

    // 内部 3n + 1
    // 外部 1 + 2n + n * (3n + 1)
    // 3n^2 + 3n + 1
    // O(n^2)
}

O(logn)

public static void test4(int n) {
    // 2 = 2^1
    // 4 = 2^2
    // 8 = 2^3
    // 16 = 2^3  4 = log2(16)

    // 如果传入16 while则执行次数 2 * (log2(n))开根号
    // O(logn)
    while ((n = n / 2) > 0) {
        System.out.println("test");
    }

    // log5(n)
    while ((n = n / 5) > 0) {
        System.out.println("test");
    }
}

斐波那契数列

image.png

image.png

错误写法 递归 O(2^n)

public static int fbi(int n) {
    if (n <= 1) {
        return n;
    }
    return fbi(n - 1) + fbi(n - 2);
}

正确写法

public static int fbi2(int n) {
    // 优化一 
    if (n <= 1) {
        return n;
    }
    int first = 0;
    int second = 1;
    for (int i = 0; i < n - 1; i++) {
        second = first + second;
        first = second - first;
    }

    // 优化二 while循环
    first = 0;
    second = 1;
    //while ((n = n -1) > 0) {
    while ((n --) > 1) {
        second = first + second;
        first = second - first;
    }
    return second;
}