LintCode-最长连续序列
来源:互联网 发布:苹果啪啪下载软件 编辑:程序博客网 时间:2024/04/29 13:22
给定一个未排序的整数数组,找出最长连续序列的长度。
要求你的算法复杂度为O(n)
解法一
对数组排序
遍历找出最长连续序列,要注意有重复数字的情况
int longestConsecutive(vector<int> &num) { // write you code here if(num.size() == 0) return 0; sort(num.begin(), num.end()); int max = 1; int cur = 1; for(int i = 1; i < num.size(); ++i) { if(num[i - 1] + 1 == num[i]) { ++cur; if(cur > max) max = cur; }else if(num[i - 1] == num[i]){ ; }else { cur = 1; } } return max; }
用哈希表来达到o(n)的时间复杂度
遍历数组,将数字放入哈希表
再次遍历数组,通过哈希表找连续序列
int longestConsecutive(vector<int> &num) { // write you code here unordered_map<int, int> map; for(int i = 0; i < num.size(); ++i) { map[num[i]] = 0; } int max = 0; for(int i = 0; i < num.size(); ++i) { if(map[num[i]] == 0) { int tmp; int cur = 1; tmp = num[i] - 1; while(map.count(tmp)) { ++cur; map[tmp] = 1; --tmp; } tmp = num[i] + 1; while(map.count(tmp)) { ++cur; map[tmp] = 1; ++tmp; } if(cur > max) { max = cur; } } } return max; }
0 0
- lintcode ----最长连续序列
- LintCode:最长连续序列
- LintCode-最长连续序列
- LintCode : 最长连续序列
- LintCode-最长连续序列
- lintcode--最长连续序列
- 最长连续序列-LintCode
- lintcode-最长连续子序列
- LintCode--最长上升连续子序列
- lintcode-最长上升连续子序列-397
- 最长上升连续子序列(LintCode)
- LintCode- 最长上升连续子序列
- lintCode刷题--最长上升连续子序列
- LintCode:最长上升连续子序列
- *[Lintcode]Longest Consecutive Sequence最长连续序列
- lintcode -- 最长上升连续子序列
- lintcode:最长上升连续子序列
- LintCode: 最长上升连续子序列
- Spring ioc
- 数据结构实验之链表九:双向链表
- 秒杀倒计时的js脚本
- appium+python环境搭建
- WorkFlow建立
- LintCode-最长连续序列
- NOIP2015 跳石头 二分
- 支付宝 ILLEGAL_SIGN 原因
- Android ActionBar的基本用法
- Flume-NG启动过程源码分析(2)
- C和指针读书笔记(第五章)
- git删除中途某一次commit
- Page object abstraction -- bdd script
- .NET DLL 保护措施详解(三)最终效果