1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/java/longest-consecutive-sequence.java
Matej Focko 1ae0cb4b89
java: add «128. Longest Consecutive Sequence»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-04 23:19:43 +02:00

33 lines
684 B
Java

import java.util.HashMap;
class Solution {
public int longestConsecutive(int[] nums) {
var uniqueNums = new HashMap<Integer, Boolean>();
for (var num : nums) {
uniqueNums.put(num, false);
}
// mark the possible starts
for (var num : nums) {
if (!uniqueNums.containsKey(num - 1)) {
uniqueNums.put(num, true);
}
}
var longest = 0;
for (var num : uniqueNums.entrySet()) {
if (!num.getValue()) {
continue;
}
var length = 1;
for (int x = num.getKey() + 1; uniqueNums.containsKey(x); ++x) {
++length;
}
longest = Math.max(longest, length);
}
return longest;
}
}