題目連結

想想看,既然是找連續數字,我們是否可以利用hash table,來幫忙做連續區間檢查呢?

AC Code

 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;

// tree node stuff here...
#endif

static int __initialSetup = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}
();

class Solution
{
public:
    // (expected O(n))
    int longestConsecutive(vector<int> &nums)
    {
        unordered_set<int> s;
        for (auto i : nums)
            s.insert(i);

        auto it = s.begin();
        int ans = 0;
        while (it != s.end()) {
            int val = *it;
            s.erase(it);
            int cnt = 1;
            // inc
            for (int i = 1;; i++) {
                if (s.find(val + i) != s.end()) {
                    cnt++;
                    s.erase(val + i);
                } else {
                    break;
                }
            }
            // dec
            for (int i = 1;; i++) {
                if (s.find(val - i) != s.end()) {
                    cnt++;
                    s.erase(val - i);
                } else {
                    break;
                }
            }

            ans = max(ans, cnt);
            it = s.begin();
        }

        return ans;
    }
    // O(nlogn)
    // int longestConsecutive(vector<int> &nums)
    // {
    //     if (nums.size() == 0)
    //         return 0;

    //     sort(nums.begin(), nums.end());
    //     {
    //         auto it = unique(nums.begin(), nums.end());
    //         nums.resize(distance(nums.begin(), it));
    //     }

    //     int ans = 1, cnt = 1;
    //     for (int i = 1; i < (int)nums.size(); i++) {
    //         if (nums[i] - 1 != nums[i - 1]) {
    //             ans = max(ans, cnt);
    //             cnt = 1;
    //         } else {
    //             cnt++;
    //         }
    //     }
    //     ans = max(ans, cnt);
    //     return ans;
    // }
};

#ifdef LOCAL
int main()
{
    vector<int> inp({100, 4, 200, 1, 3, 2});
    cout << Solution().longestConsecutive(inp) << endl;
    return 0;
}
#endif