Kodewick
開始學 →
log n 是怎麼來的3 / 52

log n 是怎麼來的

第 3 課,共 52 課 · 第 1 部分 · 起步:怎麼衡量快慢 · 約 16 分鐘

O(log n) 來自每一步把範圍砍掉一半:猜 1 到 100 的數最多 7 次,二分查詢和 STL 的 lower_bound 都是這樣。

猜一個 1 到 100 之間的數,每次只告訴你「大了」還是「小了」。最聰明的猜法是每次猜中間:50,然後 25 或 75……最多 7 次一定猜中。100 個數只要 7 步,這就是 log n。

每次砍一半

每猜一次,剩下的可能就少一半:100 → 50 → 25 → 13 → 7 → 4 → 2 → 1。從 n 一直砍到 1,砍的次數就是 log₂ n。

1024 連砍 10 次到 1:每一條都是上一條的一半,左邊數到 10,就是 log₂ 1024
main.cpp
1#include <iostream>2using namespace std;3 4int halvings(int n) {5    int steps = 0;6    while (n > 1) {7        n /= 2;8        steps++;9    }10    return steps;11}12 13int main() {14    int sizes[] = {8, 100, 1000, 1000000};15    for (int n : sizes)16        cout << "n = " << n << "  砍 " << halvings(n) << " 次\n";17    return 0;18}
輸出
n = 8  砍 3 次
n = 100  砍 6 次
n = 1000  砍 9 次
n = 1000000  砍 19 次

n 從 1000 漲到 100 萬(1000 倍),步數只從 9 漲到 19(多 10 步)。這就是 O(log n) 厲害的地方。

nlog₂ n(約)
1 00010
1 000 00020
1 000 000 00030
單選

一個 O(log n) 的演算法,n = 1000 時大約要 10 步。n 變成 2000,大約要幾步?

練習 1

砍到 1 要幾次

補全迴圈:n 每次除以 2(整數除法),直到不大於 1,數出 n = 1000 時砍了幾次。

要顯示
9
exercise1.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int n = 1000, steps = 0;6    // while 裡:n 除以 2,steps 加 17    cout << steps << "\n";8    return 0;9}
輸出
點「執行」或按 Ctrl+Enter

每次翻一倍,也是 log n

反過來想:從 1 開始每次乘 2,乘到不小於 n 要幾次?和從 n 砍到 1 是同一個數。迴圈變數每次乘一個數(而不是加一個數),就是 log n。

猜輸出猜錯也沒關係

i 每次乘 2,n = 100 時印出幾?

1#include <iostream>2using namespace std;3 4int main() {5    int n = 100, steps = 0;6    for (int i = 1; i < n; i *= 2)7        steps++;8    cout << steps << "\n";9    return 0;10}

乘 3、乘 10 也一樣是 log n,只是對數的底不同:log₃ n 和 log₂ n 只差一個固定的倍數,大 O 裡去掉係數,所以不寫底,就叫 O(log n)。

二分查詢

在排好序的數組裡找一個數,就可以這樣猜:看中間那個,比要找的小,就只在右半邊找;比它大,就只在左半邊找。

a(找 x = 9)1357911130123456↑lo↑hi
1int lo = 0, hi = n - 1;2while (lo <= hi) {3    int mid = (lo + hi) / 2;4    if (a[mid] == x) return mid;5    if (a[mid] < x) lo = mid + 1;6    else hi = mid - 1;7}8return -1;

在 7 個數裡找 9:每次看中間,丟掉不可能的一半,3 步找到
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int binary_find(const vector<int>& a, int x, int& steps) {6    int lo = 0, hi = (int)a.size() - 1;7    while (lo <= hi) {8        int mid = (lo + hi) / 2;9        steps++;10        if (a[mid] == x) return mid;11        if (a[mid] < x) lo = mid + 1;12        else hi = mid - 1;13    }14    return -1;15}16 17int main() {18    vector<int> a(1000);19    for (int i = 0; i < 1000; i++)20        a[i] = 2 * i;   // 0 2 4 … 1998,排好序21    int steps = 0;22    int at = binary_find(a, 1234, steps);23    cout << "1234 在下標 " << at << ",看了 " << steps << " 次\n";24    return 0;25}
輸出
1234 在下標 617,看了 10 次

1000 個數,最多看 10 次。順序查詢最壞要看 1000 次。

前提: 二分查詢只對排好序的陣列有用。沒排序,丟掉的那一半裡可能就有要找的數。

考試常考: n 個元素的折半查詢,查詢成功時最多比較 ⌊log₂ n⌋ + 1 次(10 個元素最多 4 次)。

填空點一個填進空格,再點空格可以拿回來

補上空格,讓二分查詢找到 11,印出它的下標 5。

1#include <iostream>2using namespace std;3 4int main() {5    int a[] = {1, 3, 5, 7, 9, 11, 13};6    int lo = 0, hi = 6, x = 11, at = -1;7    while (lo <= hi) {8        int mid = (lo + hi) / 2;9        if (a[mid] == x) { at = mid; break; }10        if (a[mid] < x) lo = ;11        else hi = mid - 1;12    }13    cout << at << "\n";14    return 0;15}
單選

1000 個排好序的數,二分查詢最多要看幾次?

練習 2

寫出二分查詢

補全 binary_find:在排好序的 a 裡找 x,找到返回下標,找不到返回 -1。

要顯示
5
-1
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int binary_find(const vector<int>& a, int x) {6    int lo = 0, hi = (int)a.size() - 1;7    // while (lo <= hi):看中間,再丟掉一半8    return -1;9}10 11int main() {12    vector<int> a = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};13    cout << binary_find(a, 23) << "\n";14    cout << binary_find(a, 7) << "\n";15    return 0;16}
輸出
點「執行」或按 Ctrl+Enter

在程式碼裡認出 log n

判斷一個迴圈是不是 log n,看迴圈變數每次怎麼變:

  • 每次加或減一個數(i++、i += 2、i--):走的次數和 n 成正比,是 O(n);
  • 每次乘或除一個數(i *= 2、n /= 2、i *= 3):幾步就到頭,是 O(log n)。
每次加 2for (i = 0; i < n; i += 2)512 次O(n):只是少走一半
每次乘 2for (i = 1; i < n; i *= 2)10 次O(log n)
n = 1024:每次加 2 要走 512 次,每次乘 2 只走 10 次

兩種迴圈套在一起:外層走 n 次,裡層每次乘 2,一共 n × log n 步,寫成 O(n log n)。它比 O(n) 慢一點,比 O(n²) 快得多;後面要學的歸併排序、堆排序就是這個漲法。

main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int sizes[] = {8, 64, 1024};6    for (int n : sizes) {7        int steps = 0;8        for (int i = 0; i < n; i++)9            for (int j = 1; j < n; j *= 2)10                steps++;11        cout << "n = " << n << "  " << steps << " 步\n";12    }13    return 0;14}
輸出
n = 8  24 步
n = 64  384 步
n = 1024  10240 步

n = 1024 時是 10240 步;要是兩層都走滿 n 次,就是 1024 × 1024,100 萬出頭。

單選

哪段程式碼是 O(log n)?

猜輸出猜錯也沒關係

外層走 n 次,裡層每次乘 2。印出幾?

1#include <iostream>2using namespace std;3 4int main() {5    int n = 32, steps = 0;6    for (int i = 0; i < n; i++)7        for (int j = 1; j < n; j *= 2)8            steps++;9    cout << steps << "\n";10    return 0;11}

用 STL 寫

<algorithm> 裡有現成的二分:binary_search(b, e, x) 只回答在不在(bool);lower_bound(b, e, x) 返回第一個不小於 x 的位置(迭代器),找不到時它正好指著 x 該插進去的地方,所以更常用。和上一課一樣,傳一個會數數的比較函式,看它比了幾次,再和從頭找的 find_if 比一比:

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a(1000);8    for (int i = 0; i < 1000; i++)9        a[i] = 2 * i;   // 0 2 4 … 199810    int steps = 0;11    auto less_count = [&](int x, int y) { steps++; return x < y; };12 13    auto it = lower_bound(a.begin(), a.end(), 1234, less_count);14    cout << "lower_bound(1234):下標 " << (it - a.begin()) << ",比較 " << steps << " 次\n";15 16    steps = 0;17    it = lower_bound(a.begin(), a.end(), 1235, less_count);18    cout << "lower_bound(1235):" << *it << ",下標 " << (it - a.begin()) << ",比較 " << steps << " 次\n";19 20    steps = 0;21    it = find_if(a.begin(), a.end(), [&](int y) { steps++; return y == 1234; });22    cout << "find_if(1234):下標 " << (it - a.begin()) << ",比較 " << steps << " 次\n";23 24    cout << boolalpha << binary_search(a.begin(), a.end(), 1234) << " "25         << binary_search(a.begin(), a.end(), 1235) << "\n";26    return 0;27}
輸出
lower_bound(1234):下標 617,比較 10 次
lower_bound(1235):1236,下標 618,比較 10 次
find_if(1234):下標 617,比較 618 次
true false

1235 不在數組裡,lower_bound 停在 1236:1235 要插進去就該放在這裡。同樣找 1234,從頭找比了 618 次,二分只比了 10 次。

從頭找find_if(b, e, ...)比較 618 次O(n)
二分lower_bound(b, e, 1234)比較 10 次O(log n)
在 0, 2, 4, …, 1998 這 1000 個排好序的數裡找 1234
寫法返回什麼代價
binary_search(b, e, x)在不在:true / falseO(log n)
lower_bound(b, e, x)第一個 ≥ x 的位置O(log n)
upper_bound(b, e, x)第一個 > x 的位置O(log n)
upper_bound − lower_boundx 出現了幾次O(log n)

它們都要求區間已經排好序(sort 一次是 O(n log n),第 0 章最後一課講)。沒排好序也能跑,只是答案是錯的,不會報錯。

面試裡: 二分題先想能不能直接用 lower_bound、upper_bound,能少寫很多邊界。要說清楚它們的區別:lower_bound 找「≥ x」,upper_bound 找「> x」。用在 set、map 上要寫成 s.lower_bound(x)(O(log n)),寫成 lower_bound(s.begin(), s.end(), x) 會一個個往後走,變成 O(n)。

猜輸出猜錯也沒關係

a 裡有三個 3。印出什麼?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {1, 3, 3, 3, 5, 8};8    auto lo = lower_bound(a.begin(), a.end(), 3);9    auto hi = upper_bound(a.begin(), a.end(), 3);10    cout << (lo - a.begin()) << " " << (hi - a.begin()) << " " << (hi - lo) << "\n";11    return 0;12}
單選

s 是一個有 n 個數的 set<int>。下面哪種找法是 O(log n)?

小結

這一課帶走

每次砍一半,就是 O(log n)

  • n = 100 萬,log₂ n 只有 20 左右
  • 每次翻一倍和每次砍一半,都是 log n
  • 二分查詢:只對排好序的陣列有用
  • STL:lower_bound 找第一個 ≥ x,upper_bound 找第一個 > x
  • 外層 n 次、裡層每次乘 2:O(n log n)
1while (lo <= hi) {2    int mid = (lo + hi) / 2;3    if (a[mid] == x) return mid;4    if (a[mid] < x) lo = mid + 1; else hi = mid - 1;5}6auto it = lower_bound(a.begin(), a.end(), x);