标签:
1. 把所有元素都塞到集合里
2. 遍历所有元素,对于每个元素,如果集合里没有,就算了,如果有的话,就向左向右拓展,找到最长的连续范围,同时在每次找的时候都把找到的删掉。这样做保证了同样的连续序列只会被遍历一次,从而保证时间复杂度。
时间复杂度O(n)
代码:
1 int longestConsecutive(vector<int> &num) { 2 set<int> record; 3 int maxLength = 0; 4 5 for (auto n : num) 6 record.insert(n); 7 8 while (!record.empty()) { 9 int len = 1; 10 int n = *(record.begin()); 11 record.erase(n); 12 for (int i = n - 1; record.find(i) != record.end(); i--) { 13 len++; 14 record.erase(i); 15 } 16 for (int i = n + 1; record.find(i) != record.end(); i++) { 17 len++; 18 record.erase(i); 19 } 20 maxLength = max(maxLength, len); 21 } 22 23 return maxLength;
Leetcode#128 Longest Consecutive Sequence
标签:
原文地址:http://www.cnblogs.com/boring09/p/4236402.html