Skip to content
Algorithm.js
📚 단일 패턴

128. Longest Consecutive Sequence

정렬되지 않은 배열에서 HashSet을 사용하여 O(n) 시간 복잡도로 가장 긴 연속된 숫자 시퀀스 찾기

Sep 30, 2025 — set

문제 설명

풀이 아이디어

구현

/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
if (!nums || nums.length === 0) return 0;
let length = 0;
const set = new Set(nums);
let max = 1;
for (const num of set) {
if (!set.has(num - 1)) {
let length = 1;
let cur = num;
while (set.has(cur + 1)) {
cur += 1;
length += 1;
}
if (max < length) max = length;
}
}
return max;
};