Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions longest-consecutive-sequence/reach0908.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* time complexity: O(n log n)
* space complexity: O(n)
* runtime: 57ms
* 풀이 방법: 중복을 제거하고 정렬한 다음에 연속된 숫자의 개수를 카운트하여 최대값을 반환한다.
* @param {number[]} nums
* @return {number}
*/
const longestConsecutive = function (nums) {
if (nums.length === 0) return 0;
const sortedNums = [...new Set(nums)].sort((a, b) => a - b);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정렬이 꼭 필요한 문제는 아니라고 생각이 듭니다. 정렬을 쓰면 nlogn으로 시간복잡도가 올라가니깐 정렬 없는 풀이도 한번 생각해보시면 도움이 될 거 같습니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 문제 한번 개선해보고 있습니다!


let maxConsecutiveCount = 1;
let currentConsecutiveCount = 1;

for (let i = 1; i < sortedNums.length; i += 1) {
if (sortedNums[i] === sortedNums[i - 1] + 1) {
currentConsecutiveCount += 1;
} else {
currentConsecutiveCount = 1;
}

maxConsecutiveCount = Math.max(
maxConsecutiveCount,
currentConsecutiveCount
);
}

return maxConsecutiveCount;
};