/**
* Runtime: 24 ms, faster than 64.64%
* Memory Usage: 54.5 MB, less than 46.79%
*/
class Solution {
public int longestConsecutive(int[] nums) {
int max = 0;
HashMap<Integer, Integer> map = new HashMap<>();
// remove duplication
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
// calculate max
for (int num : set) {
int leftLen = map.getOrDefault(num - 1, 0);
int rightLen = map.getOrDefault(num + 1, 0);
int currentSum = leftLen + 1 + rightLen;
max = Math.max(max, currentSum);
// update max length at boundaries, as it is only possible to extend max length when boundaries are broaden
map.put(num - leftLen, currentSum); // update the max length at left bound
map.put(num + rightLen, currentSum); // update the max length at right bound
}
return max;
}
}
128. Longest Consecutive Sequence [Medium]
最新推荐文章于 2024-05-14 20:06:41 发布