思路:

维护一个unordered_map,key是每个连续区间的端点,value是该区间的长度。

实现:

 1 class Solution
 2 {
 3 public:
 4     int longestConsecutive(vector<int>& nums) 
 5     {
 6         unordered_map<int, int> mp;
 7         int ans = 0;
 8         for (auto it: nums)
 9         {
10             if (mp.count(it)) continue;
11             int l = mp.count(it - 1) ? mp[it - 1] : 0;
12             int r = mp.count(it + 1) ? mp[it + 1] : 0;
13             int sum = l + r + 1;
14             ans = max(ans, sum);
15             mp[it] = sum;
16             mp[it - l] = sum;
17             mp[it + r] = sum;
18         }
19         return ans;
20     }
21 };

 

相关文章:

  • 2021-04-18
  • 2021-06-08
  • 2021-10-12
  • 2021-11-14
  • 2021-09-03
猜你喜欢
  • 2021-09-10
  • 2022-12-23
  • 2021-12-15
  • 2021-05-28
  • 2021-10-12
相关资源
相似解决方案