Skip to content

Commit

Permalink
solve: longest consecutive sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
wogha95 committed Sep 2, 2024
1 parent 77d6e59 commit 5a921e5
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions longest-consecutive-sequence/wogha95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* TC: O(N)
* SC: O(N)
* nums์˜ ์ˆซ์ž์— ์ ‘๊ทผํ•˜๋Š” ํšŸ์ˆ˜๋Š” 2๋ฒˆ์—์„œ N๋งŒํผ, 4๋ฒˆ์—์„œ ์ตœ๋Œ€ N๋งŒํผ ์ž…๋‹ˆ๋‹ค.
* ์ฆ‰, 2N๋ฒˆ ๋งŒํผ nums์˜ ์ˆซ์ž์— ์ ‘๊ทผํ•ฉ๋‹ˆ๋‹ค.
*/

/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function (nums) {
let maxCount = 0;
const obj = {};

// 1. ์ˆซ์ž์˜ ์กด์žฌ ์—ฌ๋ถ€๋ฅผ ํ‚ค๋กœ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด ์ €์žฅ
for (const num of nums) {
obj[num] = true;
}

// 2. ์‹œ์ž‘์ ๋“ค์„ ์ฐพ๊ธฐ ์œ„ํ•ด ์ˆœํšŒ
for (const num of nums) {
// 3. ์—ฐ์†์ ์ธ ๋ฐฐ์—ด์˜ ์‹œ์ž‘์ ์ธ์ง€ ํ™•์ธ
if (obj[num - 1]) {
continue;
}

// 4. ์—ฐ์†์ ์ธ ๋ฐฐ์—ด์˜ ์‹œ์ž‘์ ๋ถ€ํ„ฐ ๋์ ๊นŒ์ง€ ์ˆœํšŒ
let count = 1;
let next = num + 1;
while (obj[next]) {
count += 1;
next += 1;
}

// 5. ๊ฐ€์žฅ ๊ธด ๋ฐฐ์—ด์˜ ๊ธธ์ด ๊ฐฑ์‹ 
maxCount = Math.max(maxCount, count);
}

return maxCount;
};

0 comments on commit 5a921e5

Please sign in to comment.