LeetCode - Longest Consecutive Sequence
来源:互联网 发布:陕西民爆系统网络平台 编辑:程序博客网 时间:2024/04/25 17:27
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.
采用两个HashMap,一个存放在序列最小值,及其对应的长度。另一个存放序列最大值,及其对应的长度,要注意的时候,对这两个map中值的更新操作。
public class Solution { public int longestConsecutive(int[] num) { // Start typing your Java solution below // DO NOT write main() function Map<Integer, Integer> big = new HashMap<Integer, Integer>(); Map<Integer, Integer> small = new HashMap<Integer, Integer>(); int max = 1; for (int i=0; i<num.length; i++) { int value = num[i]; if (big.get(value)!=null || small.get(value)!=null) continue; if (big.get(value-1)!=null && small.get(value+1)!=null) { big.put(value, 1); int l1 = big.get(value-1); int l2 = small.get(value+1); int length = l1+l2+1; big.put(value+l2, length); small.put(value-l1, length); max = Math.max(max, length); } else if (big.get(value-1) != null) { int length = big.get(value-1)+1; big.put(value, length); small.put(value-length+1, length); max = Math.max(max, length); } else if (small.get(value+1) != null) { int length = small.get(value+1)+1; small.put(value, length); big.put(value+length-1, length); max = Math.max(max, length); } else { big.put(value, 1); small.put(value, 1); } } return max; }}
- Leetcode : Longest Consecutive Sequence
- [Leetcode] Longest Consecutive Sequence
- [leetcode] longest consecutive sequence
- 【leetcode】Longest Consecutive Sequence
- LeetCode - Longest Consecutive Sequence
- [LeetCode]Longest Consecutive Sequence
- leetcode:Longest Consecutive Sequence
- [Leetcode]Longest Consecutive Sequence
- [leetcode]Longest Consecutive Sequence
- leetcode Longest Consecutive Sequence
- Leetcode: Longest Consecutive Sequence
- LeetCode:Longest Consecutive Sequence
- [leetcode] Longest Consecutive Sequence
- LeetCode-Longest Consecutive Sequence
- LeetCode - Longest Consecutive Sequence
- [LeetCode] longest consecutive sequence
- LeetCode | Longest Consecutive Sequence
- [leetcode]Longest Consecutive Sequence
- 毕业之后,要做的
- 外国的一篇关于ARC的文章
- 全国软件3.考察团组成
- Android wifi驱动之earlysuspend睡眠模式
- c++读取配置文件
- LeetCode - Longest Consecutive Sequence
- 计数排序
- AnimationDrawable动画实现
- 哀
- 对象池commons-pool框架的研究以及源代码分析(六)总结
- LeetCode —— Word Search
- UVA11384 - Help is needed for Dexte(正整数序列)
- Java:谈谈protected访问权限
- C/C++文件输入输出操作——FILE*、fstream、windowsAPI