128. Longest Consecutive Sequence
来源:互联网 发布:怎样优化win7开机时间 编辑:程序博客网 时间:2024/06/04 01:41
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.
要求O(n)的时间复杂度,一般都是用空间换时间,这个题目利用unordered_set比较简单
class Solution {public: int longestConsecutive(vector<int>& nums) { unordered_set<int> record(nums.begin(),nums.end()); int res=0; for(int n:nums){ if(record.find(n)==record.end()) continue; record.erase(n); int prev=n-1,post=n+1; while(record.find(prev)!=record.end()) record.erase(prev--); while(record.find(post)!=record.end()) record.erase(post++); res=max(res,post-prev-1); } return res; }};
阅读全文
0 0
- 128.Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- 128. Longest Consecutive Sequence
- java中的快速失败(fail-fast)与安全失败(fail-safe)
- 特斯拉为什么要造电动卡车?
- 网狐荣耀版手机端在复制文本时提示“复制内容非法”的解决办法
- 共享自己电脑硬盘空间还能赚钱?
- Protues8示波器的使用
- 128. Longest Consecutive Sequence
- 循环与回调函数
- 让而莫争 放而莫贪
- 《TP5.0学习笔记---对Mysql数据库的操作(二)》
- Android常用颜色
- 性能测试的流程
- SpringMVC之File "/WEB-INF/jsp/validate/demo2.jsp" not found
- JAVA中的反射机制
- 高并发量网站解决方案