2 map<
int,
int> mapping;
3 int max = 0;
4 // The start point for the longest chain
5 int start = 0;
6
7 for (
int i=0; i<size; i++) {
8 if (mapping.find(list[i]) == mapping.end()) {
9 int cur = list[i];
10 // Set current position as the start point for this potential longest chain
11 int cur_start = cur;
12 mapping.insert(make_pair(cur, 1));
13
14 map<
int,
int>::iterator prev = mapping.find(cur - 1);
15 map<
int,
int>::iterator next = mapping.find(cur + 1);
16
17 if (prev != mapping.end()) {
18 // If previous number exists, increase current consecutive count
19 mapping[cur] = prev->second + 1;
20 }
21
22 if (next != mapping.end()) {
23 // Update the last one in the chain with the consecutive count from the one before current position
24 int last = next->first + next->second - 1;
25 mapping[last] = mapping[cur] = mapping[cur] + mapping[last];
26 }
27
28 if (prev != mapping.end()) {
29 // Update the first one in the chain with the consecutive count from the one after current position
30 int first = prev->first - prev->second + 1;
31 mapping[first] = mapping[cur];
32
33 // Use the first one as the start point for the whole chain
34 cur_start = first;
35 }
36
37 if (mapping[cur_start] > max) {
38 start = cur_start;
39 max = mapping[cur_start];
40 }
41 }
42 }
43
44 cout << "Longest consecutive items:";
45 for (
int i=0; i<max; i++) {
46 cout << " " << start + i;
47 }
48 cout << endl;
49
50 return max;
51 }
瀹屾暣浠g爜