思路:
维护一个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 };