Skip to content

Commit 150d179

Browse files
committed
Add solution #128
1 parent 9961cfb commit 150d179

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

solutions/0128-longest-consecutive-sequence.js

+11-8
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
* https://leetcode.com/problems/longest-consecutive-sequence/
44
* Difficulty: Medium
55
*
6-
* Given an unsorted array of integers nums, return the length of the
7-
* longest consecutive elements sequence.
6+
* Given an unsorted array of integers nums, return the length of the longest consecutive
7+
* elements sequence.
88
*
99
* You must write an algorithm that runs in O(n) time.
1010
*/
@@ -17,13 +17,16 @@ var longestConsecutive = function(nums) {
1717
const set = new Set(nums);
1818
let result = 0;
1919

20-
for (let i = 0; i < nums.length; i++) {
21-
if (!set.has(nums[i] - 1)) {
22-
let streak = 1;
23-
while (set.has(nums[i] + streak)) {
24-
streak++;
20+
for (const num of set) {
21+
if (!set.has(num - 1)) {
22+
let count = 1;
23+
let n = num;
24+
25+
while (set.has(n + 1)) {
26+
n++;
27+
count++;
2528
}
26-
result = Math.max(result, streak);
29+
result = Math.max(result, count);
2730
}
2831
}
2932

0 commit comments

Comments
 (0)