[LeetCode] Longest Consecutive Sequence, Solution

本文介绍了一种利用哈希表解决寻找无序整数数组中最长连续序列长度的方法,通过三个步骤实现O(n)复杂度的解决方案。

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given  [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is  [1, 2, 3, 4]. Return its length:  4.
Your algorithm should run in O( n) complexity.

» Solve this problem

[Thoughts]
Since it requires O(n) solution, normal sort won’t be work here. Hash probably is the best choice.
3 Steps:
1. create the hashmap to hold <num, index>
2. scan the num vector from left to right, for each num
               i, check whether num -1 is in the map  (loop)
              ii, check whether num+1 is in the map  (loop)
3. track the sequence length during scanning.

[Code]

1:       int longestConsecutive(vector<int> &num) {  
2: unordered_map<int, int> hashmap;
3: for(int i =0; i< num.size(); i++)
4: {
5: hashmap[num[i]] = i;
6: }
7: vector<int> visited(num.size(), 0);
8: int maxV = INT_MIN;
9: for(int i =0; i< num.size(); i++)
10: {
11: if(visited[i]==1) continue;
12: visited[i]=1;
13: int len = 1;
14: int index = num[i]-1;
15: while(hashmap.find(index) != hashmap.end())
16: {
17: visited[hashmap[index]] =1;
18: index--;
19: len++;
20: }
21: index = num[i]+1;
22: while(hashmap.find(index) != hashmap.end())
23: {
24: visited[hashmap[index]] =1;
25: index++;
26: len++;
27: }
28: if(len > maxV)
29: maxV = len;
30: }
31: return maxV;
32: }

Update 08/23/2014
Interesting discussion in the comments:) I haven’t visited my blog for quite long time.

For each num, define D[num] as the longest consecutive sequence from k to num,  0<k<num

So D[num] = D[num-1] +1   if num-1 in the map
                  =0                      if num-1  not in the map

But unfortunately, the unordered_map doesn’t keep any order of sequence. It’s hard to do the DP via a loop.

Here can use Memorization to optimize the code. Since for each fresh node, it only visits once. It is O(n) code.

And in the code , the second ‘for’ loop and the third ‘for’ loop could be merged together, but here keep them separated for readability.

1:       int longestConsecutive(vector<int> &num) {  
2: unordered_map<int, int> hashmap;
3: vector<int> length(num.size(),0);
4: for(int i =0; i< num.size(); i++)
5: {
6: hashmap[num[i]]=i;
7: }
8: for(int i =0; i< num.size(); i++)
9: {
10: // skip the node, which already calculate the length
11: if(length[i] > 0) continue;
12: length[i] = consecutiveLength(num[i], hashmap, length);
13: }
14: int maxV = INT_MIN;
15: for(int i =0; i< num.size(); i++)
16: {
17: maxV = length[i]>maxV?length[i]:maxV;
18: }
19: return maxV;
20: }
21: int consecutiveLength(int num, unordered_map<int, int>& hashmap, vector<int>& length)
22: {
23: if(hashmap.find(num) == hashmap.end()) return 0;
24: int index = hashmap[num];
25: // skip the node, which already calculate the length
26: if(length[index] > 0) return length[index];
27: else
28: {
29: // hit each fresh node only once
30: length[index] = consecutiveLength(num - 1, hashmap, length) + 1;
31: return length[index];
32: }
33: }
基于径向基函数神经网络RBFNN的自适应滑模控制学习(Matlab代码实现)内容概要:本文介绍了基于径向基函数神经网络(RBFNN)的自适应滑模控制方法,并提供了相应的Matlab代码实现。该方法结合了RBF神经网络的非线性逼近能力和滑模控制的强鲁棒性,用于解决复杂系统的控制问题,尤其适用于存在不确定性和外部干扰的动态系统。文中详细阐述了控制算法的设计思路、RBFNN的结构与权重更新机制、滑模面的构建以及自适应律的推导过程,并通过Matlab仿真验证了所提方法的有效性和稳定性。此外,文档还列举了大量相关的科研方向和技术应用,涵盖智能优化算法、机器学习、电力系统、路径规划等多个领域,展示了该技术的广泛应用前景。; 适合人群:具备一定自动控制理论基础和Matlab编程能力的研究生、科研人员及工程技术人员,特别是从事智能控制、非线性系统控制及相关领域的研究人员; 使用场景及目标:①学习和掌握RBF神经网络与滑模控制相结合的自适应控制策略设计方法;②应用于电机控制、机器人轨迹跟踪、电力电子系统等存在模型不确定性或外界扰动的实际控制系统中,提升控制精度与鲁棒性; 阅读建议:建议读者结合提供的Matlab代码进行仿真实践,深入理解算法实现细节,同时可参考文中提及的相关技术方向拓展研究思路,注重理论分析与仿真验证相结合。
<think>好的,我现在需要帮助用户理解他们提供的C++代码段。首先,我会仔细阅读代码,看看它做了什么。 代码中有两个部分:首先声明了一个`unordered_set<int> num_set;`,然后遍历`nums`中的每个元素,将它们插入到`num_set`中。作者是力扣官方题解,可能这段代码是用于解决最长连续序列问题的。 用户可能想知道这段代码的作用以及它在特定问题中的用途。需要解释`unordered_set`的特点,比如快速查找、去重等。然后循环部分,将`nums`中的每个元素插入到集合中,这样可以去重,并为后续的查找操作做准备。 接下来要考虑用户可能的背景。可能是刚开始学习C++或者算法,对STL容器不熟悉。需要用简单易懂的语言解释,避免使用过多术语,但又要准确。比如,解释`unordered_set`是基于哈希表实现的,插入和查找的平均时间复杂度是O(1),这样在处理大量数据时效率高。 然后,这段代码可能出现在最长连续序列的问题中,比如LeetCode 128题。那个问题需要找到一个未排序数组中数字连续的最长序列的长度。通常的解法是先利用集合去重,然后遍历每个数字,检查是否是序列的起点,再逐次查找下一个数字是否存在。因此,这个`num_set`的创建是为了后续的查找操作,提高效率。 用户可能没有说明具体的应用场景,但根据代码来源,可以推测是用于这个问题。需要指出这段代码的作用是预处理数据,去重并存储在哈希集合中,以便快速查询。 另外,需要注意代码中的细节,比如循环中使用`const int& num`来避免不必要的拷贝,提高效率。虽然对于基本类型int来说,用不用引用区别不大,但这也是一种良好的编程习惯。 最后,要确保解释清晰,结构合理,先介绍代码的结构,再解释每个部分的作用,最后联系到实际问题中的应用,帮助用户全面理解。</think>这段代码的作用是**将数组 `nums` 中的所有元素存入一个哈希集合(`unordered_set`)中,实现去重和快速查找**。以下是逐行解析: --- ### 代码解析 ```cpp unordered_set<int> num_set; // 1. 声明一个无序集合(基于哈希表实现) for (const int& num : nums) { // 2. 遍历数组 nums 中的每个元素 num num_set.insert(num); // 3. 将 num 插入集合(自动去重) } ``` --- ### 关键点说明 1. **`unordered_set` 的特性**: - **去重**:若 `nums` 中有重复元素,集合中只会保留一个。 - **快速查找**:基于哈希表实现,插入和查找的平均时间复杂度为 $O(1)$。 - **无序存储**:元素不按顺序存储(与 `set` 不同)。 2. **循环的作用**: - 将数组 `nums` 的每个元素存入集合,为后续操作(如“检查某个值是否存在”)做准备。 --- ### 典型应用场景(如 LeetCode 128. 最长连续序列) 在这类问题中,这段代码常用于: 1. **去重**:避免重复元素干扰连续序列的计算。 2. **快速查询**:后续通过 `num_set.count(num+1)` 等操作,快速判断某个值是否存在,从而统计连续序列长度。 --- ### 代码对比:为什么用 `unordered_set` 而不是其他容器? | 容器 | 特点 | |------------------|---------------------------------------------------------------------| | `vector` | 不去重,查找效率低($O(n)$) | | `set` | 自动排序,但插入和查找效率为 $O(\log n)$ | | `unordered_set` | 无序,但插入和查找效率最高($O(1)$),**最适合当前需求** | --- ### 示例说明 假设输入 `nums = [3, 1, 2, 2, 4]`,执行代码后: - `num_set` 中的内容为 `{1, 2, 3, 4}`(去重且无序存储)。 - 后续可通过 `num_set.find(3)` 快速判断数字 `3` 是否存在。 --- ### 总结 这段代码是**预处理数据的常见操作**,核心目的是通过哈希集合实现: 1. 去重 2. 为后续高频查找提供 $O(1)$ 时间复杂度的支持
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值