原题地址

 

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;

 

相关文章:

  • 2021-05-17
  • 2021-04-18
  • 2021-09-27
猜你喜欢
  • 2021-08-16
  • 2021-06-17
  • 2021-11-02
  • 2021-10-21
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案