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

/**
* Using hashmap to reduce time complexity to O(n);
* the space complexity is O(n)
*/
#include <vector> #include <map> using namespace std; int longestConsecutive(vector<int> &num) { map<int, int> cluster; int longest = 0; size_t size = num.size(); for (int i = 0; i < size; ++i) { int n = num[i]; int &seqs = cluster[n]; if (seqs != 0) continue; seqs = 1; int lower = cluster[n-1]; if (lower != 0) { seqs = lower + 1; // update boundary cluster[n-lower] = seqs; } int upper = cluster[n+1]; if (upper != 0) { seqs = seqs + upper; // update boundary cluster[n+upper] = seqs; cluster[n-lower] = seqs; } if (longest < seqs) { longest = seqs; } } return longest; }
View Program Text


Test Status