1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

java: add «128. Longest Consecutive Sequence»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-04 23:19:43 +02:00
parent 0e4bb92726
commit 1ae0cb4b89
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,33 @@
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;
}
}