-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSequence.java
More file actions
50 lines (46 loc) · 1.49 KB
/
LongestConsecutiveSequence.java
File metadata and controls
50 lines (46 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package hard;
import java.util.HashSet;
/**
*
* ClassName: LongestConsecutiveSequence
* @author chenyiAlone
* Create Time: 2019/04/22 16:15:14
* Description: No.128
* 思路:
* 1. 题目要求时间复杂度为 O(N) 所以这道题不能进行排序,也就只能使用 Hash 来做,当
* bucket 的数量够大时那么查找的时间复杂就可以近似到 O(1)
* 2. 使用 HashSet 既能排除掉重复元素
* 3. 数组非有序,需要从正反双向进行查找
*
*
* Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
*
*
*/
public class LongestConsecutiveSequence {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int n : nums) {
set.add(n);
}
int res = 0;
for (int n : nums) {
int count = 1;
for (int i = n + 1; set.contains(i); i++) {
set.remove(i);
count++;
}
for (int i = n - 1; set.contains(i); i--) {
set.remove(i);
count++;
}
res = Math.max(res, count);
}
return res;
}
}