Kodewick
開始學 →
題型與套路:堆疊和佇列17 / 52

題型與套路:堆疊和佇列

第 17 課,共 52 課 · 第 3 部分 · 堆疊和佇列 · 約 20 分鐘

這一課複習堆疊和佇列最常考的三類題:判斷出堆疊序列是否合法、用兩個堆疊實現佇列、用單調堆疊求下一個更大的數,先手寫,再用 std::stack 寫。

堆疊和佇列本身不難,難的是看出一道題該用哪個、怎麼用。這一課的三類題(外加迴圈佇列的計算題)在期末、考研 408 和麵試裡反覆出現,每類記住一個套路。

套路一:出堆疊序列合不合法

第一課手算過:入堆疊順序 1 2 3,出堆疊順序 3 1 2 不可能。寫成程式就是照著做一遍:按順序 push,每 push 一個,就看堆疊頂是不是下一個該出的,是就一直 pop。最後堆疊空了,說明這個出堆疊順序做得到。

堆疊

入堆疊順序 1 2 3,想要的出堆疊順序是 3 1 2:照著做一遍
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5// 入堆疊順序是 1, 2, …, n;out 是想要的出堆疊順序6bool valid(const vector<int>& out) {7    int n = out.size();8    int st[100], t = -1, k = 0;9    for (int x = 1; x <= n; x++) {10        st[++t] = x;11        while (t >= 0 && st[t] == out[k]) {12            t--;13            k++;14        }15    }16    return t == -1;17}18 19int main() {20    vector<vector<int>> tests = {{3, 2, 1}, {3, 1, 2}, {2, 4, 3, 1}, {4, 1, 2, 3}};21    for (const vector<int>& p : tests) {22        for (int x : p)23            cout << x << " ";24        cout << (valid(p) ? "可以" : "不行") << "\n";25    }26    return 0;27}
輸出
3 2 1 可以
3 1 2 不行
2 4 3 1 可以
4 1 2 3 不行

每個數最多進一次、出一次:O(n)。

單選

入堆疊順序是 1 2 3 4 5,哪一個不可能是出堆疊順序?

練習 1

判斷出堆疊序列

補全 valid:入堆疊順序是 1 到 n,判斷 out 能不能是出堆疊順序。

要顯示
1 0 1
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5bool valid(const vector<int>& out) {6    int n = out.size();7    int st[100], t = -1, k = 0;8    for (int x = 1; x <= n; x++) {9        // push x;堆疊頂等於 out[k] 就一直 pop,k++10    }11    return t == -1;12}13 14int main() {15    cout << valid({1, 3, 2}) << " " << valid({3, 1, 2}) << " " << valid({4, 3, 5, 2, 1}) << "\n";16    return 0;17}
輸出
點「執行」或按 Ctrl+Enter

套路二:兩個堆疊做一個佇列

面試常問:只有堆疊,怎麼做出先進先出?用兩個:in 只管進,out 只管出。出隊時 out 空了,就把 in 裡的全部倒進 out:順序一倒,最早進來的正好到了 out 的堆疊頂。

in

out

兩個堆疊做佇列:1 2 3 進了 in,出隊時 out 是空的,把 in 倒過去,最早的 1 就在 out 頂上
main.cpp
1#include <iostream>2using namespace std;3 4class TwoStackQueue {5    int in[100], out[100];6    int tin = -1, tout = -1;               // 兩個堆疊的堆疊頂下標7public:8    void enqueue(int x) {9        in[++tin] = x;10    }11    int dequeue() {12        if (tout == -1)                    // out 空了才倒13            while (tin >= 0)14                out[++tout] = in[tin--];15        return out[tout--];16    }17};18 19int main() {20    TwoStackQueue q;21    q.enqueue(1);22    q.enqueue(2);23    q.enqueue(3);24    cout << q.dequeue() << " ";25    q.enqueue(4);26    cout << q.dequeue() << " ";27    cout << q.dequeue() << " ";28    cout << q.dequeue() << "\n";29    return 0;30}
輸出
1 2 3 4

關鍵是只在 out 空的時候才倒:out 裡還有東西就倒,新來的會壓在老的上面,順序就亂了。每個元素一輩子只被倒一次,所以雖然某次出隊可能要倒很多個,平均下來每次是 O(1)(均攤,和 vector 容量翻倍是一個道理)。

單選

in 裡從堆疊底到堆疊頂是 1 2 3,out 是空的。出隊一次以後,out 裡從堆疊底到堆疊頂是什麼?

練習 2

兩個堆疊做佇列

補全 pop:out 空了才把 in 全部倒過去,再從 out 出。

要顯示
5 6 7
exercise2.cpp
1#include <iostream>2#include <stack>3using namespace std;4 5class MyQueue {6    stack<int> in, out;7public:8    void push(int x) { in.push(x); }9    int pop() {10        // out 空:把 in 一個個取出來 push 進 out11        if (out.empty()) return -1;   // 倒過以後還是空,才說明佇列空了12        int x = out.top();13        out.pop();14        return x;15    }16};17 18int main() {19    MyQueue q;20    q.push(5);21    q.push(6);22    cout << q.pop() << " ";23    q.push(7);24    cout << q.pop() << " ";25    cout << q.pop() << "\n";26    return 0;27}
輸出
點「執行」或按 Ctrl+Enter

套路三:單調堆疊,下一個更大的數

題目:對每個數,找它右邊第一個比它大的數,沒有就是 −1。兩層迴圈是 O(n²)。套路是單調堆疊:堆疊裡放還沒找到答案的數的下標,它們從堆疊底到堆疊頂是遞減的。來了一個新數,比堆疊頂大,堆疊頂的答案就是它,pop;一直到堆疊頂不比它小,再把它 push。

a2153401234↑i
st(堆疊裡的下標,堆疊底在左)

單調堆疊求「下一個更大的數」:2 1 5 3 4。堆疊裡放還在等答案的下標,新數一來先把比它小的都結算掉
main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int a[] = {2, 1, 5, 3, 4}, n = 5;6    int ans[5], st[5], t = -1;7    for (int i = 0; i < n; i++) {8        while (t >= 0 && a[i] > a[st[t]])9            ans[st[t--]] = a[i];       // 堆疊頂等到了10        st[++t] = i;11    }12    while (t >= 0)13        ans[st[t--]] = -1;             // 一直沒等到14    for (int i = 0; i < n; i++)15        cout << ans[i] << " ";16    cout << "\n";17    return 0;18}
輸出
5 5 -1 4 -1 

每個下標進堆疊一次、出堆疊一次:O(n)。「下一個更大 / 更小」「每日溫度」「柱狀圖裡最大的矩形」都是這個套路。

單選

a = 3 1 4 2,每個數「右邊第一個比它大的數」依次是什麼(沒有就是 −1)?

練習 3

下一個更小的數

和課上相反:對每個數找右邊第一個比它小的數,沒有就是 −1。用 vector<int> 當單調堆疊。

要顯示
3 3 1 1 -1
exercise3.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {4, 6, 3, 5, 1};7    int n = a.size();8    vector<int> ans(n, -1), st;9    for (int i = 0; i < n; i++) {10        // 新數比堆疊頂小:堆疊頂的答案就是它,pop11        st.push_back(i);12    }13    for (int x : ans)14        cout << x << " ";15    cout << "\n";16    return 0;17}
輸出
點「執行」或按 Ctrl+Enter

迴圈佇列的計算題

考試會換著花樣定義 rear。先看清楚 rear 指的是隊尾元素還是下一個空位,公式跟著變:

rear 指著長度隊滿
下一個空位(這門課的寫法)(rear - front + MAX) % MAX(rear + 1) % MAX == front
隊尾元素本身(rear - front + 1 + MAX) % MAX(rear + 2) % MAX == front

考試常考: 「用陣列 A[0..n] 實現迴圈佇列」說的是 n + 1 個格子,MAX = n + 1,別當成 n。

單選

MAX = 10 的迴圈佇列,這次 rear 指著隊尾元素本身。front = 7,rear = 2,隊裡有幾個?

用 STL 寫

面試裡這三個套路都不手寫陣列。單調堆疊最常用 vector<int> 當堆疊:push_back、back、pop_back,和 stack<int> 一樣是 O(1),還能隨時看堆疊裡所有的下標。下面是「每日溫度」:每天要等幾天才會更暖和,答案是下標的差,這就是堆疊裡放下標、不放值的原因。

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> temp = {73, 74, 75, 71, 69, 72, 76, 73};7    int n = temp.size();8    vector<int> wait(n, 0);            // 一直等不到就是 09    vector<int> st;                    // 當堆疊用:存下標10    for (int i = 0; i < n; i++) {11        while (!st.empty() && temp[i] > temp[st.back()]) {12            wait[st.back()] = i - st.back();13            st.pop_back();14        }15        st.push_back(i);16    }17    for (int w : wait)18        cout << w << " ";19    cout << "\n";20    return 0;21}
輸出
1 1 4 2 1 1 0 0 

兩個堆疊做佇列換成兩個 stack<int>,再數一數一共倒了多少個元素:

main.cpp
1#include <iostream>2#include <stack>3using namespace std;4 5class MyQueue {6    stack<int> in, out;7public:8    int moves = 0;                     // 一共倒了幾個元素9    void push(int x) { in.push(x); }10    int pop() {11        if (out.empty())12            while (!in.empty()) {13                out.push(in.top());14                in.pop();15                moves++;16            }17        int x = out.top();18        out.pop();19        return x;20    }21};22 23int main() {24    MyQueue q;25    int pops = 0, last = 0;26    for (int i = 1; i <= 1000; i++) {27        q.push(i);28        if (i % 3 == 0) {29            last = q.pop();30            pops++;31        }32    }33    cout << pops << " 次出隊,最後出來的是 " << last << ",一共倒了 " << q.moves << " 個\n";34    return 0;35}
輸出
333 次出隊,最後出來的是 333,一共倒了 363 個

333 次出隊一共只倒了 363 個元素,平均每次一個多一點:這就是均攤 O(1)。每個元素最多被倒一次,倒的總數不會超過入隊的總數。

套路用什麼每個元素一共
出堆疊序列stack<int> 或陣列進一次、出一次O(n)
兩個堆疊做佇列兩個 stack<int>最多倒一次每次均攤 O(1)
單調堆疊vector<int> 存下標進一次、出一次O(n)

面試裡: 看到「右邊(左邊)第一個更大 / 更小」就想單調堆疊,堆疊裡放下標;「用堆疊實現佇列」考的是隻在 out 空時才倒,以及均攤分析;反過來「用佇列實現堆疊」是每次 push 後把前面的元素繞到隊尾,push 變成 O(n)。真寫程式碼要先進先出時,直接用 queue<int> 或 deque<int>。

單選

用兩個 stack<int> 做的 MyQueue:push 1、2、3,pop,push 4、5,pop,pop,pop。moves(一共倒了幾個元素)最後是幾?

小結

這一課帶走

堆疊和佇列三個套路

  • 出堆疊序列:照著 push,堆疊頂該出就 pop,最後堆疊空才合法
  • 兩個堆疊做佇列:out 空了才把 in 倒過去,均攤 O(1)
  • 單調堆疊:堆疊裡放等答案的下標,新數一來先結算比它小的
  • STL:stack / queue 是 deque 外面的一層;單調堆疊常用 vector
1while (!st.empty() && a[i] > a[st.back()]) {2    ans[st.back()] = a[i];3    st.pop_back();4}5st.push_back(i);

第 2 章快刷

5 道題,覆蓋迴圈佇列、字尾表示式、括號匹配、兩個堆疊做佇列和出堆疊序列。先自己算出印出什麼,再點選項。

猜輸出猜錯也沒關係

MAX = 5 的迴圈佇列(rear 指著下一個空位),front = 3,rear = 1,裡面有幾個?

1#include <iostream>2using namespace std;3 4const int MAX = 5;5 6int main() {7    int front = 3, rear = 1;8    cout << (rear - front + MAX) % MAX << "\n";9    return 0;10}
猜輸出猜錯也沒關係

算字尾表示式 2 3 * 5 4 * + 9 −,印出幾?

1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6int main() {7    string s = "23*54*+9-";8    stack<int> st;9    for (char c : s) {10        if (c >= '0' && c <= '9') {11            st.push(c - '0');12        } else {13            int b = st.top(); st.pop();14            int a = st.top(); st.pop();15            st.push(c == '+' ? a + b : c == '-' ? a - b : a * b);16        }17    }18    cout << st.top() << "\n";19    return 0;20}
猜輸出猜錯也沒關係

檢查 {[()()]} 時,堆疊裡最多同時有幾個括號?

1#include <iostream>2#include <string>3#include <algorithm>4using namespace std;5 6int main() {7    string s = "{[()()]}";8    int height = 0, best = 0;9    for (char c : s) {10        if (c == '(' || c == '[' || c == '{') height++;11        else height--;12        best = max(best, height);13    }14    cout << best << "\n";15    return 0;16}
猜輸出猜錯也沒關係

兩個堆疊做的佇列:入 1 2,出,入 3 4,再出兩次,印出什麼?

1#include <iostream>2#include <stack>3using namespace std;4 5stack<int> in, out;6 7void enqueue(int x) { in.push(x); }8 9int dequeue() {10    if (out.empty())11        while (!in.empty()) {12            out.push(in.top());13            in.pop();14        }15    int x = out.top();16    out.pop();17    return x;18}19 20int main() {21    enqueue(1);22    enqueue(2);23    cout << dequeue() << " ";24    enqueue(3);25    enqueue(4);26    cout << dequeue() << " ";27    cout << dequeue() << "\n";28    return 0;29}
猜輸出猜錯也沒關係

入堆疊順序 1 2 3 4,一共有幾種合法的出堆疊順序?(next_permutation 把 24 種排列都試了一遍)

1#include <iostream>2#include <algorithm>3using namespace std;4 5bool valid(const int* out, int n) {6    int st[10], t = -1, k = 0;7    for (int x = 1; x <= n; x++) {8        st[++t] = x;9        while (t >= 0 && st[t] == out[k]) {10            t--;11            k++;12        }13    }14    return t == -1;15}16 17int main() {18    int p[] = {1, 2, 3, 4}, count = 0;19    do {20        if (valid(p, 4)) count++;21    } while (next_permutation(p, p + 4));22    cout << count << "\n";23    return 0;24}