Skip to content

Commit a6a966b

Browse files
author
이호찬
committed
refactor longest-consecutive-sequence
1 parent 3c9ea58 commit a6a966b

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

longest-consecutive-sequence/lhc0506.js

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,25 @@
22
* @param {number[]} nums
33
* @return {number}
44
*/
5+
56
var longestConsecutive = function(nums) {
67
const numSet = new Set(nums);
78

89
let maxLength = 0;
910
let currentLength = 0;
1011

11-
nums.forEach(num => {
12+
const countConsecutive = (num, step) => {
1213
let currentNum = num;
1314
while(numSet.has(currentNum)) {
14-
numSet.delete(currentNum)
15-
currentNum += 1;
15+
numSet.delete(currentNum);
16+
currentNum += step;
1617
currentLength += 1;
1718
}
19+
}
1820

19-
currentNum = num - 1;
20-
while(numSet.has(currentNum)) {
21-
numSet.delete(currentNum)
22-
currentNum -= 1;
23-
currentLength += 1;
24-
}
21+
nums.forEach(num => {
22+
countConsecutive(num, 1);
23+
countConsecutive(num - 1, -1);
2524

2625
maxLength = Math.max(maxLength, currentLength);
2726
currentLength = 0;

0 commit comments

Comments
 (0)