128. Longest Consecutive Sequence
来源:互联网 发布:php教程网源码 编辑:程序博客网 时间:2024/05/21 22:50
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.
https://discuss.leetcode.com/topic/6148/my-really-simple-java-o-n-solution-accepted/2
We will use HashMap. The key thing is to keep track of the sequence length and store that in the boundary points of the sequence. For example, as a result, for sequence {1, 2, 3, 4, 5}, map.get(1) and map.get(5) should both return 5.
Whenever a new element n is inserted into the map, do two things:
- See if n - 1 and n + 1 exist in the map, and if so, it means there is an existing sequence next to n. Variables left and right will be the length of those two sequences, while 0 means there is no sequence and n will be the boundary point later. Store (left + right + 1) as the associated value to key n into the map.
- Use left and right to locate the other end of the sequences to the left and right of n respectively, and replace the value with the new length.
public int longestConsecutive(int[] num) { int res = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int n : num) { if (!map.containsKey(n)) { int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0; int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0; // sum: length of the sequence n is in int sum = left + right + 1; map.put(n, sum); // keep track of the max length res = Math.max(res, sum); // extend the length to the boundary(s) // of the sequence // will do nothing if n has no neighbors map.put(n - left, sum); map.put(n + right, sum); } else { // duplicates continue; } } 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中的异常
- js学习笔记(比较全)
- Python.Extracting Data from XML
- hdu2026 首字母变大写
- 128. Longest Consecutive Sequence
- c++游戏别踩白块课程设计
- 心里藏着一个人,怎么能开始一段新的感情
- c语言_函数指针的调用方法
- 【HDU】4135 - Co-prime(容斥原理)
- 杭电-4883 TIANKENG’s restaurant
- gradle多渠道打包
- 定义一个长方形类,定义 求周长和面积的方法,然后定义一个测试了Test2,进行测试
- 【 CodeForces 698B 】Vacations