34 lines
684 B
Java
34 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;
|
||
|
}
|
||
|
}
|