mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
33 lines
684 B
Java
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;
|
|
}
|
|
}
|