java: add «128. Longest Consecutive Sequence»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
0e4bb92726
commit
1ae0cb4b89
1 changed files with 33 additions and 0 deletions
33
java/longest-consecutive-sequence.java
Normal file
33
java/longest-consecutive-sequence.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue