-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution128.java
47 lines (36 loc) · 1.13 KB
/
Solution128.java
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
package array_problem;
import java.util.HashMap;
public class Solution128 {
public int longestConsecutive(int[] nums) {
// 1、创建 值:频率 哈希表
HashMap<Integer, Integer> countForNum = new HashMap<>();
for (int num:nums) {
countForNum.put(num, 1);
}
// 2、求出哈希表中每一个值对应的最大序列长度
for (int num:nums) {
forward(countForNum, num);
}
// 3、统计哈希表中存储的最大序列长度
return maxLen(countForNum);
}
private int forward(HashMap<Integer, Integer> countForNum, int num) {
if (!countForNum.containsKey(num)) {
return 0;
}
int cnt = countForNum.get(num);
if (cnt > 1) {
return cnt;
}
cnt = forward(countForNum, num + 1) + 1;
countForNum.put(num, cnt);
return cnt;
}
private int maxLen(HashMap<Integer, Integer> countForNum) {
int max = 0;
for (int num:countForNum.keySet()) {
max = Math.max(max, countForNum.get(num));
}
return max;
}
}