極客算法訓練營 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.

 示例

題目

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 階乘

注:只看最高複雜度的運算

Master Theorem

維基-主定理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章