Skip to content

Commit 378093f

Browse files
committed
fix: remove sort
1 parent 5f8eaac commit 378093f

File tree

1 file changed

+12
-26
lines changed

1 file changed

+12
-26
lines changed

longest-consecutive-sequence/tolluset.ts

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,44 +3,30 @@
33
* SC: O(n)
44
* */
55
function longestConsecutive(nums: number[]): number {
6-
const consecutives = [...new Set(nums.sort((a, b) => b - a))];
7-
const n = consecutives.length;
6+
const n = nums.length;
87

98
if (n <= 1) {
109
return n;
1110
}
1211

13-
const bucket = [...Array(n)].map((): Set<number> => new Set());
14-
15-
let cursor = 0;
12+
const numsSet = new Set(nums);
13+
let longestLen = 0;
1614

1715
for (let i = 0; i < n; i++) {
18-
const current = consecutives[i];
19-
const left = consecutives[i - 1];
20-
const right = consecutives[i + 1];
21-
22-
const isLeft = left !== undefined && left - current === 1;
23-
const isRight = right !== undefined && current - right === 1;
24-
25-
const isConsecutive = isLeft || isRight;
16+
let current = nums[i];
2617

27-
if (isConsecutive) {
28-
bucket[cursor].add(current);
18+
if (!numsSet.has(current - 1)) {
19+
let currentLen = 1;
2920

30-
if (isLeft && !isRight) {
31-
cursor++;
21+
while (numsSet.has(current + 1)) {
22+
current++;
23+
currentLen++;
3224
}
33-
} else {
34-
cursor++;
25+
26+
longestLen = Math.max(longestLen, currentLen);
3527
}
3628
}
37-
38-
const total = bucket.reduce(
39-
(acc, cur) => (acc > cur.size ? acc : cur.size),
40-
0,
41-
);
42-
43-
return total === 0 ? 1 : total;
29+
return longestLen;
4430
}
4531

4632
const t1 = longestConsecutive([100, 4, 200, 1, 3, 2]);

0 commit comments

Comments
 (0)