-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode128.java
More file actions
27 lines (23 loc) · 782 Bytes
/
LeetCode128.java
File metadata and controls
27 lines (23 loc) · 782 Bytes
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
class Solution {
public int longestConsecutive(int[] nums) {
// Q1. Does it has duplicate number in array nums?
// Q2. Can you give me an example?
// Tips:
// 1. Use HashSet to store the numbers in the array. This will help us check if nums + 1 and nums - 1 exist.
Set<Integer> set = new HashSet<>();
int result = 0;
for (int num : nums){
set.add(num);
}
for (int num : set){
if (!set.contains(num - 1)){
int currentLength = 1;
while(set.contains(num + currentLength)){
currentLength ++;
}
result = Math.max(result, currentLength);
}
}
return result;
}
}