-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path128.最长连续序列.java
42 lines (35 loc) · 916 Bytes
/
128.最长连续序列.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
/*
* @lc app=leetcode.cn id=128 lang=java
*
* [128] 最长连续序列
*/
// @lc code=start
import java.util.HashSet;
import java.util.Set;
class Solution {
public int longestConsecutive(int[] nums) {
return longestConsecutiveHash(nums);
}
int longestConsecutiveHash(int[] nums) {
// from leetcode official
// just use hashset to store elements in nums
Set<Integer> numsEle = new HashSet<>();
for (Integer num : nums) {
numsEle.add(num);
}
// calculate maxLen
int maxLen = 0;
for (Integer num : nums) {
if (numsEle.contains(num - 1)) {
continue;
}
int i = 1;
while (numsEle.contains(i + num)) {
i++;
}
maxLen = Math.max(maxLen, i);
}
return maxLen;
}
}
// @lc code=end