Longest Consecutive Sequence 最长连续子序列
2014-08-10 23:21
134 查看
题目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
Return its length:
Your algorithm should run in O(n) complexity.
解答:
哈希 空间换时间
代码:
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.
解答:
哈希 空间换时间
代码:
class Solution { public: map<int, int> mp; int longestConsecutive(vector<int> &num) { int i, j; for(i = 0; i < num.size(); i++) mp[num[i]] = 1; int max = 0; for(i = 0; i < num.size(); i++) { int sum = 1; if(mp.count(num[i])){ mp[num[i]] = 0; int left = num[i] -1; while(mp.count(left) && mp[left] != 0) { mp[left--] = 0; sum++; } int right = num[i] + 1; while(mp.count(right) && mp[right] != 0){ mp[right++] = 0; sum++; } } if(max < sum) max = sum; } return max; } };
相关文章推荐
- HDU 1003 Max Sum(最长连续子序列和)
- 动态规划——最长连续子序列和+最大子矩阵和
- HDU 3308 线段树。。最长连续上升子序列
- 最长连续递增子序列
- 3. Longest Substring Without Repeating Characters(求最长的不重复的连续的子序列。)
- 最长连续子序列和的线性算法及其他算法
- HDU 3308——LCIS(线段树,区间合并,最长连续递增子序列)
- 最长连续递增子序列
- hdu1069-最长连续上升子序列
- 51Nod - 1241 特殊的排序(求最长连续递增子序列)
- HDU 3308 LCIS(最长连续上升子序列)(线段树区间合并)
- 最长连续子序列
- 习题3.4 最长连续递增子序列
- 最长上升子序列(非连续)
- 求数组中最长的连续子序列
- 最长连续递增子序列
- Codeforces Round #335 (Div. 2) C. Sorting Railway Cars 最长连续上升子序列
- 5-1 最长连续递增子序列
- 线段树区间合并+最长连续递增子序列——HDU 3308
- 矩阵中最长连续递增子序列