最长连续序列
来源:互联网 发布:仓库办公软件 编辑:程序博客网 时间:2024/05/02 01:00
题目:给定一个未排序的整数数组,找出最长连续序列的长度。
例子:给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4。
挑战:要求你的算法复杂度为O(n)。
方法:。将序列中的所有数存到一个unordered_set中。对于序列里任意一个数A[i],我们可以通过set马上能知道A[i]+1和A[i]-1是否也在序列中。如果在,继续找A[i]+2和A[i]-2,以此类推,直到将整个连续序列找到。为了避免在扫描到A[i]-1时再次重复搜索该序列,在从每次搜索的同时将搜索到的数从set中删除。直到set中为空时,所有连续序列搜索结束。由于每个数字只被插入set一次,并删除一次,所以算法是O(n)的。
class Solution {public: int longestConsecutive(vector<int>& nums) { unordered_map<int, bool> hash; for (int i = 0; i < nums.size(); i++) { hash[nums[i]] = true; } int max = 0; for (int i = 0; i < nums.size(); i++) { int up = nums[i]; while (hash.find(up) != hash.end()) { hash.erase(up); up++; } int down = nums[i] - 1; while (hash.find(down) != hash.end()) { hash.erase(down); down--; } if (up - down - 1 > max) { max = up - down - 1; } } return max; }};
0 0
- 【最长连续序列问题】
- 最长连续序列
- 最长连续序列
- 最长连续序列
- 连续最长子序列
- 最长连续子序列
- 最长连续序列
- 最长连续序列
- lintcode ----最长连续序列
- 最长连续序列长度
- 最长连续子序列
- LintCode:最长连续序列
- LintCode-最长连续序列
- 最长连续序列
- LintCode : 最长连续序列
- 最长连续序列
- 最长连续序列
- LintCode-最长连续序列
- HTML入门
- java学习之Calender类
- 获取手机里所有的app并点击相应的图标开启相应的程序
- MySQL 5.5 服务器变量详解
- Java http get与post请求
- 最长连续序列
- Spring MVC handler interceptors example
- 忍忍
- word转pdf还有什么好的方法
- 设定字符串字符的颜色
- iOS界面设计切图小结
- Uva 11582 Colossal Fibonacci Numbers! 快速幂,斐波那契
- LeetCode_OJ【15】3Sum
- POJ1753 Flip Game【高斯消元法】