From 7e2ba7c4acefc7f16860a1b2c94eda8cb1c9a8ca Mon Sep 17 00:00:00 2001 From: BangDori Date: Fri, 13 Jun 2025 13:02:20 +0900 Subject: [PATCH] =?UTF-8?q?[=EA=B0=95=EB=B3=91=EC=A4=80]=20Longest=20Conse?= =?UTF-8?q?cutive=20Sequence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bangdori/128.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 bangdori/128.js diff --git a/bangdori/128.js b/bangdori/128.js new file mode 100644 index 0000000..53d0e18 --- /dev/null +++ b/bangdori/128.js @@ -0,0 +1,32 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const set = new Set(nums); + const visited = new Set(); + let answer = 0; + let count = 0; + + const dfs = (num) => { + count++; + visited.add(num); + + if (set.has(num + 1) && !visited.has(num + 1)) { + dfs(num + 1); + } + + if (set.has(num - 1) && !visited.has(num - 1)) { + dfs(num - 1); + } + }; + + for (const num of set) { + if (visited.has(num)) continue; + count = 0; + dfs(num); + answer = Math.max(answer, count); + } + + return answer; +};