class Solution {public: int longestConsecutive(vector<int> &num) { int len = num.size(); int max_cons = 0; int cur_cons = 0; unordered_map<int, int> sgn; unordered_map<int, int>::iterator iter; for (int i=0; i<len; i++) { sgn.insert(make_pair(num[i], 0x1)); } for (int i=0; i<len; i++) { iter = sgn.find(num[i]); if (iter == sgn.end()) continue; // illegal case, should not hit if (iter->second == 0) continue; // this range has been scaned iter->second = 0; cur_cons = 1; int try_n = num[i]; // search towards negative while (try_n != INT_MIN) { try_n--; iter = sgn.find(try_n); if (iter == sgn.end()) break; iter->second = 0; cur_cons++; } try_n = num[i]; // search towards positive while (try_n != INT_MAX) { try_n++; iter = sgn.find(try_n); if (iter == sgn.end()) break; iter->second = 0; cur_cons++; } if (cur_cons > max_cons) max_cons = cur_cons; } return max_cons; }};
The most intuitive method is to sort the logs and scan the logs from the front to the back. However, the sorting takes nlogn time and must be completed within O (n) time, certainly not based on comparative sorting. You can sort buckets, but the int range is large and not desirable. The sparse representation is put into the hash table. The first time the array is traversed, a hash table entry with elements as key and 1 as value is inserted, for the second time, the previous query attempts to find the forward and backward values of each element in the hash table. If so, the query proceeds to the forward or backward query, updating the continuous count cur_cons, at the same time, the value of the continuously scanned hash table item is set to zero, indicating that the item has been scanned, so as to avoid repeated detection.