极客算法训练营 0x0 基础及复杂度分析

自顶向下的编程方式

The best idea in this book for me was the newspaper metaphor that is mentioned with regards to formatting your code. This describes the idea of making code read like a newspaper article. We should be able to get a general idea of how it works near the top of the class before reading more and more details further down. This can be achieved by breaking the code out into lots of small methods. It was strange how involved I got with the newspaper metaphor. Having read about it early on I started looking at all code after that to be in that format and when it wasn’t (when showing examples of not such clean code) I became disappointed.

 示例

题目

极客算法训练营 0x0 基础及复杂度分析_第1张图片

code

/**
 * @param {string} s
 * @return {boolean}
 */
const isPalindrome = function(s) {
    const lowStr = getLowerCaseStr(s)
    const filterStr = getFilterStr(lowStr)
    const reverseStr = getReverseStr(filterStr)
    return filterStr === reverseStr
};
function getLowerCaseStr(s) {
    return s.toLowerCase()
}
function getFilterStr(s) {
    return s.replace(/[^0-9A-Za-z]/g,'')
}
function getReverseStr(s) {
    return s.split('').reverse().join('')
}

解题步骤

  1. 弄清题目
  2. 想出尽可能多的解法,分析时间和空间复杂度
  3. 找出最优解
  4. 测试

时间复杂度

Big O notation

O(1): Constant Complexity 常数复杂度

int n = 1000;
System.out.prinln(n);

O(log n):Logarithmic Complexity 对数复杂度

for (int i = 1; i < n; i = i * 2) {
    System.out.println(i);
}

O(n): LInear Complexity 线性时间复杂度

for (init i = 1; i <= n; i++) {
    System.out.println(i);
}

O(n^2): N square Complexity 平方

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        System.out.println(i,j);
    }
}

O(n^3): N cube Complexity 立方

O(k^n):Exponential Growth 指数

int fib (int n) {
    if (n <= 2) return n;
    return fib(n-1) + fib(n-2);
}

O(n!): Factorial 阶乘

注:只看最高复杂度的运算

极客算法训练营 0x0 基础及复杂度分析_第2张图片

Master Theorem

维基-主定理

极客算法训练营 0x0 基础及复杂度分析_第3张图片

你可能感兴趣的:(数据结构)