[LeetCode] 128. Longest Consecutive Sequence 解题思路
2015-12-28 00:54
459 查看
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
Your algorithm should run in O(n) complexity.
问题:给定一个无序数组,找出最长的连续序列,要求时间复杂度为 O(n) 。
一开始想到的是用先排序,再找结果,但是时间复杂度要求 O(n) ,使用排序会超时。
思索未果,再网上找到一个方案,借助 unordered_set 来实现。
将元素全部塞进 unordered_set 中。
取出 unordered_set 中的一个剩余元素 x ,找到 unordered_set 中 x 的全部前后相邻元素,并将 x 和相邻元素全部移除,此时能得到 x 的相邻长度。若 unordered_set 还有元素,则继续当前步骤。
在第二步中的所有相邻长度中,找出最大值便是原问题的解。
由于 unordered_set 是基于 hash_table 来实现的,所以每次插入、查找、删除都是 O(1),而全部元素只会 插入、查找、删除 1 次,所以整体复杂度是 O(n)。
参考资料:
[LeetCode] Longest Consecutive 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.
问题:给定一个无序数组,找出最长的连续序列,要求时间复杂度为 O(n) 。
一开始想到的是用先排序,再找结果,但是时间复杂度要求 O(n) ,使用排序会超时。
思索未果,再网上找到一个方案,借助 unordered_set 来实现。
将元素全部塞进 unordered_set 中。
取出 unordered_set 中的一个剩余元素 x ,找到 unordered_set 中 x 的全部前后相邻元素,并将 x 和相邻元素全部移除,此时能得到 x 的相邻长度。若 unordered_set 还有元素,则继续当前步骤。
在第二步中的所有相邻长度中,找出最大值便是原问题的解。
由于 unordered_set 是基于 hash_table 来实现的,所以每次插入、查找、删除都是 O(1),而全部元素只会 插入、查找、删除 1 次,所以整体复杂度是 O(n)。
int longestConsecutive(vector<int>& nums) { unordered_set<int> theSet; for (int i = 0 ; i < nums.size(); i++) { theSet.insert(nums[i]); } int longest = 0; while (theSet.size() > 0 ) { int tmp = *theSet.begin(); theSet.erase(tmp); int cnt = 1; int tmpR = tmp + 1; while (theSet.count(tmpR)) { cnt++; theSet.erase(tmpR); tmpR++; } int tmpL = tmp - 1; while (theSet.count(tmpL)) { cnt++; theSet.erase(tmpL); tmpL--; } longest = max( longest, cnt); } return longest; }
参考资料:
[LeetCode] Longest Consecutive Sequence, 喜刷刷
相关文章推荐
- uinavigationcontrollerdemo
- EasyUI表单内容整理
- Masonry自动计算行高
- juery动态添加删除表格中的行
- iOS UITableView(三) 为tableView添加图片实现电话薄
- 对UIView动画和Core Animation的关系的一点理解
- 《MVC + EasyUI 》——利用Ajax给Action传值
- Ant之build.xml详解
- 解决UNIX环境高级变成中找不到apue.h问题
- Unique Snowflakes
- iOS之浅谈纯代码控制UIViewController视图控制器跳转界面的几种方法
- Subsequence-二分
- 【转】How-To-Ask-Questions-The-Smart-Way
- LeetCode之Divide and Conquer题目汇总
- 如何利用TableView显示自定义nib中创建的UITableViewCell或子类?
- 透明UI设计
- 给一个视图添加圆角效果
- 怎么设置随机色
- STL学习三:deque容器
- 20151226--easyUI