Skip to content

Commit 0dfca5c

Browse files
author
bhan
committed
edit longest consecutive sequence solution
1 parent 4f0c3ba commit 0dfca5c

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

โ€Žlongest-consecutive-sequence/byol-han.js

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,21 @@
33
* @return {number}
44
*/
55
var longestConsecutive = function (nums) {
6-
if (nums.length === 0) return 0;
6+
if (nums.length === 0) return nums.length;
77

8-
const numSet = new Set(nums);
9-
let longest = 0;
10-
for (let num of numSet) {
11-
// `num - 1`์ด ์—†์œผ๋ฉด ์ƒˆ๋กœ์šด ์ˆ˜์—ด์˜ ์‹œ์ž‘์ 
12-
if (!numSet.has(num - 1)) {
13-
let count = 1;
14-
let currentNum = num;
8+
const setNums = new Set(nums);
9+
const sortNums = [...setNums].sort((a, b) => a - b);
1510

16-
// ์—ฐ์†๋œ ์ˆซ์ž ์ฐพ๊ธฐ
17-
while (numSet.has(currentNum + 1)) {
18-
currentNum++;
19-
count++;
20-
}
11+
let longest = 1;
12+
let currentlength = 1;
2113

22-
longest = Math.max(longest, count);
14+
for (let i = 0; i < sortNums.length; i++) {
15+
if (sortNums[i] + 1 === sortNums[i + 1]) {
16+
currentlength++;
17+
longest = Math.max(longest, currentlength);
18+
} else {
19+
currentlength = 1;
2320
}
2421
}
25-
2622
return longest;
2723
};

0 commit comments

Comments
ย (0)