[LeetCode-128] Longest Consecutive Sequence
Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
用unordered_set装起来,来回找就ok了~
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int longestConsecutive(vector<int> &num) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int max_length = 0, tmp_length = 0, tmp_num = 0; 7 unordered_set<int> num_set; 8 num_set.clear(); 9 10 for (vector<int>::iterator iter = num.begin(); 11 iter != num.end(); ++iter) { 12 num_set.insert(*iter); 13 } 14 for (vector<int>::iterator iter = num.begin(); 15 iter != num.end(); ++iter) { 16 if (num_set.end() != num_set.find(*iter)) { 17 tmp_length = 1; 18 // find 19 tmp_num = *iter; 20 for (;;) { 21 ++tmp_num; 22 if (num_set.end() != num_set.find(tmp_num)) { 23 num_set.erase(tmp_num); 24 ++tmp_length; 25 } else { 26 break; 27 } 28 } 29 tmp_num = *iter; 30 for (;;) { 31 --tmp_num; 32 if (num_set.end() != num_set.find(tmp_num)) { 33 num_set.erase(tmp_num); 34 ++tmp_length; 35 } else { 36 break; 37 } 38 } 39 if (tmp_length > max_length) { 40 max_length = tmp_length; 41 } 42 } 43 } 44 return max_length; 45 } 46 };