最长连续序列
2015-10-09 21:23
260 查看
给定一个未排序的整数数组,找出最长连续序列的长度。
样例
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
说明 要求你的算法复杂度为O(n)
样例
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
说明 要求你的算法复杂度为O(n)
class Solution { public: /** * @param nums: A list of integers * @return an integer */ int longestConsecutive(vector<int> &num) { // write you code here int n = num.size(); int result = 0; set<int> buf; for (int i = 0; i < n; i++) { buf.insert(num[i]); } for (int i = 0; i < n; i++) { int left = maxLen(0, num[i], buf); int right = maxLen(1, num[i]+1, buf); if (left+right > result) { result = left + right; } } return result; } private: int maxLen(int flag, int val, set<int> &buf) { int result = 0; while (buf.find(val) != buf.end()) { result++; buf.erase(val); if (flag == 0) { val--; } else { val++; } } return result; } };
相关文章推荐
- flash插件如何生成
- Mac环境下SVN的使用
- ggplot2学习笔记之标度scale
- 操作系统内核Hack:(二)底层编程基础
- “钱三篇”后续之复利小结
- 移动数组中的0
- iOS开源项目学习——开源中国iOS客户端
- hdu3461Code Lock【并查集+快速幂】
- 操作系统内核Hack:(二)底层编程基础
- 键盘录入数据存到文件中
- 51nod 正整数分组(dp_思考题)
- Java窗口居中
- Ubuntu Chromium安装Flash Player
- LeetCode(118) Pascal's Triangle
- Codeforces Round #320 (Div. 2) 578A. A Problem about Polyline
- Android Studio基本设置
- 前端javascript模板
- 【iOS】多线程GCD
- LeetCode(118) Pascal's Triangle
- 01.Elasticsearch安装