[LeetCode] Longest Consecutive Sequence

本文介绍了一个关于数组中连续序列最大长度的问题解决方案,包括三种不同的实现方式:使用unordered_set、unordered_map和合并两种方法。每种方法的时间复杂度均为O(n),通过遍历数组并查找左右邻居元素来扩展序列长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This problem is not very intuitive at first glance. However, the final idea should be very self-explanatory. You visit each element in nums, and then find its left and right neighbors and extend the length accordingly. The time complexity is O(n) if we guard from visiting the same element again.

You can implement it using an unordered_set or unordered_map.

The code is as follows. The last one is taken from this page which includes a nice explanation in the follong answers.

 1 // O(n) solution using unordered_set
 2 int longestConsecutive(vector<int>& nums) {
 3     unordered_set<int> copy(nums.begin(), nums.end());
 4     unordered_set<int> filter;
 5     int len = 0;
 6     for (int i = 0; i < nums.size(); i++) {
 7         if (filter.find(nums[i]) != filter.end()) continue;
 8         int l = nums[i] - 1, r = nums[i] + 1;
 9         while (copy.find(l) != copy.end()) filter.insert(l--);
10         while (copy.find(r) != copy.end()) filter.insert(r++);
11         len = max(len, r - l - 1);
12     }
13     return len;
14 }
15 
16 // O(n) solution using unordered_map
17 int longestConsecutive(vector<int>& nums) {
18     unordered_map<int, int> mp;
19     int len = 0;
20     for (int i = 0; i < nums.size(); i++) {
21         if (mp[nums[i]]) continue;
22         mp[nums[i]] = 1;
23         if (mp.find(nums[i] - 1) != mp.end())
24             mp[nums[i]] += mp[nums[i] - 1];
25         if (mp.find(nums[i] + 1) != mp.end())
26             mp[nums[i]] += mp[nums[i] + 1];
27         mp[nums[i] - mp[nums[i] - 1]] = mp[nums[i]]; // left boundary
28         mp[nums[i] + mp[nums[i] + 1]] = mp[nums[i]]; // right boundary
29         len = max(len, mp[nums[i]]);
30     }
31     return len;
32 }
33 
34 // O(n) super-concise solution (merging the above cases)
35 int longestConsecutive(vector<int>& nums) {
36     unordered_map<int, int> mp;
37     int len = 0;
38     for (int i = 0; i < nums.size(); i++) {
39         if (mp[nums[i]]) continue;
40         len = max(len, mp[nums[i]] = mp[nums[i] - mp[nums[i] - 1]] = mp[nums[i] + mp[nums[i] + 1]] = mp[nums[i] - 1] + mp[nums[i] + 1] + 1);
41     }
42     return len;
43 }

转载于:https://www.cnblogs.com/jcliBlogger/p/4572028.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值