-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestConsecutive.js
More file actions
45 lines (35 loc) · 922 Bytes
/
longestConsecutive.js
File metadata and controls
45 lines (35 loc) · 922 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
const m = new Map();
for (const num of nums) {
m.set(num, true);
}
let longestStreak = 0;
for (const num of nums) {
let currentNum = num;
let currentStreak = 1;
while (m.get(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
return longestStreak;
};
// var longestConsecutive = function(nums) {
// nums = nums.sort((a, b) => a > b);
// let longestStreak = 1;
// let currentStreak = 1;
// for (let i = 0, len = nums.length; i < len; i++) {
// if (nums[i] - nums[i - 1] === 1) {
// currentStreak += 1;
// } else {
// longestStreak = Math.max(currentStreak, longestStreak);
// currentStreak = 1;
// }
// }
// return Math.max(longestStreak, currentStreak);
// };