LeetCode题解2.1.6
来源:互联网 发布:华尔街英语 知乎 编辑:程序博客网 时间:2024/05/27 09:46
2.1.6 Longest Consecutive Sequence
描述Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, Given [100, 4, 200, 1, 3, 2], longest consecutive elements sequence is [1,2, 3, 4]. Return its length: 4.Your algorithm should run in O(n) complexity.
public static int solution2_1_6(int num[]){if(num.length==0)return 0;if(num.length==1)return 1;else{HashSet<Integer> tempSet=new HashSet<Integer>();for(int i=0;i<num.length;i++)tempSet.add(num[i]);int maxLen=1;for(int i=0;i<num.length;i++){int tempLen=1;int temp=num[i]+1;while(tempSet.contains(temp)){//对于HashSet可以在O(1)的时间复杂度内判断是否存在该元素tempSet.remove(temp);tempLen++;temp++;}temp=num[i]-1;while(tempSet.contains(temp)){tempSet.remove(temp);tempLen++;temp--;}if(tempLen>maxLen)maxLen=tempLen;if(tempLen>num.length)break;}return maxLen;}}
0 0
- LeetCode题解2.1.6
- leetcode-个人题解6
- LeetCode 6 ZigZag Conversion题解
- LeetCode题解-6-ZigZag Conversion
- LeetCode 6 ZigZag Conversion 题解
- leetcode题解
- leetcode题解
- LeetCode 题解
- leetCode题解
- leetcode题解
- leetcode题解
- leetcode题解
- LeetCode题解
- LeetCode题解
- Leetcode题解
- Leetcode题解
- Leetcode题解
- Leetcode题解
- 简析——SQL注入
- HDU 1754 I Hate It // 线段树
- The high signification of the modified poplar plywood
- codeVS第二次月赛 C
- Qt中如何用指针返回参数
- LeetCode题解2.1.6
- AndroidStudio -快捷键
- mysql内置函数汇总
- 66Plus One
- HDU 2602 Bone Collector
- 该文件没有与之关联的程序来执行操作。解决方案
- NOIP 2010 导弹拦截 排序+贪心
- static 关键字的作用
- 中文编码杂谈