单调栈和单调队列可以用来降低一些查找问题的时间复杂度。
内容待补充。
LintCode 1316
本题对于算法的时间复杂度要求较高。 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57class Solution {
public:
    /**
     * @param arr: the arr
     * @return: the sum of the luck number
     */
    static bool pairComByFirst(pair<int, int>a, pair<int, int>b) {
        return a.first < b.first;
    }
    int luckNumber(vector<int>& arr) {
        int n = arr.size();
        int ans = 0;
        vector<pair<int, int>> a;
        for (int i = 0; i < n; i++) {
            a.emplace_back(pair<int, int>(arr[i], i));
        }
        sort(a.begin(), a.end(), pairComByFirst);
        vector<int> l(n, 0), r(n, 0);
        stack<pair<int, int>> s;
        pair<int, int> fir(0, 0);
        for (int i = 0; i < n; i++) {
            while (!s.empty()) {
                fir = s.top();
                if (a[i].second < fir.second) {
                    l[fir.second] = a[i].first;
                    s.pop();
                }
                else {
                    break;
                }
            }
            s.push(a[i]);
        }
        while (!s.empty()) {
            s.pop();
        }
        for (int i = n - 1; i >= 0; i--) {
            while (!s.empty()) {
                fir = s.top();
                if (a[i].second > fir.second) {
                    r[fir.second] = a[i].first;
                    s.pop();
                }
                else {
                    break;
                }
            }
            s.push(a[i]);
        }
        for (int i = 1; i < n - 1; i++) {
            if (l[i] && r[i] && l[i] % r[i] == 0) {
                ans++;
            }
        }
        return ans;
    }
};