-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSequence.java
More file actions
54 lines (45 loc) · 1.42 KB
/
Copy pathLongestConsecutiveSequence.java
File metadata and controls
54 lines (45 loc) · 1.42 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
51
52
53
54
import java.util.HashSet;
import java.util.Set;
// My take
// class Solution {
// public int longestConsecutive(int[] nums) {
// int longest = 0;
// Map<Integer, ArrayList<Integer>> numMap = new HashMap<>();
// Set<Integer> lookedForSet = new HashSet<>();
// for (Integer num : nums) {
// if (lookedForSet.contains(num)) {
// // Add to the hashmap
// // check if the list's length is greater than current longest
// lookedForSet.remove(num);
// }
// else {
// numMap.put(num, new ArrayList<>());
// numMap.get(num).add(num);
// }
// lookedForSet.add(num+1);
// lookedForSet.add(num-1);
// }
// }
// }
// Nie moge sortowac
// Musze zalozyc ze kazda kolejna liczba jest wazna i o niej pamietac
// Correct Solution
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
int longest = 0;
for (Integer integer : nums) {
set.add(integer);
}
for (Integer num : nums) {
if (!set.contains(num-1)) {
int length = 0;
while (set.contains(num + length)) {
length+= 1;
}
longest = Math.max(length, longest);
}
}
return longest;
}
}