kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

Difficulty: Hard

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

1
2
3
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.

Solution

Language: Java

UnionFind

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
51
52
53
54
55
56
57
58
59
60
class Solution {
class UnionFind {
Map<Integer, Integer> map;
int[] nums;
public UnionFind(int[] nums) {
this.nums = nums;
this.map = new HashMap<>();
for (int n : nums) {
add(n);
}
}

private int find(int num) {
int ancestor = map.getOrDefault(num, num);
if (ancestor != num) {
ancestor = find(ancestor);
}
map.put(num, ancestor);
return ancestor;
}

private void add(int num) {
find(num);
if (map.containsKey(num - 1)) {
union(num, num - 1);
}
if (map.containsKey(num + 1)) {
union(num, num + 1);
}
}

private void union(int a, int b) {
int ancestorA = find(a);
int ancestorB = find(b);
map.put(ancestorA, ancestorB);
}

public int longestConsecutive() {
int longest = 0;
Map<Integer, Integer> countMap = new HashMap<>();
for (int val : map.values()) {
int ancestor = find(val);
int newLen = countMap.getOrDefault(ancestor, 0) + 1;
countMap.put(ancestor, newLen);
if (newLen > longest) {
longest = newLen;
}
}
return longest;
}
}

public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
UnionFind uf = new UnionFind(nums);
return uf.longestConsecutive();
}
}

HashSet

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
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}

int longestStreak = 0;

for (int num : num_set) {
if (!num_set.contains(num-1)) {
int currentNum = num;
int currentStreak = 1;

while (num_set.contains(currentNum+1)) {
currentNum += 1;
currentStreak += 1;
}

longestStreak = Math.max(longestStreak, currentStreak);
}
}

return longestStreak;
}
}