File size: 1,306 Bytes
4b876a7 | 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | // Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
// Your algorithm should run in O(n) complexity.
// Example:
// Input: [100, 4, 200, 1, 3, 2]
// Output: 4
// Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
/**
* @param {number[]} nums
* @return {number}
* score:30.77(80ms)
* time:O(nlogn)
* space:O(n)
*/
var longestConsecutive = function (nums) {
nums = Array.from(new Set(nums));
if (nums.length < 1) {
return 0;
}
nums.sort((a, b) => a - b);
let max = 1;
let cur = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] - nums[i - 1] === 1) {
cur++;
} else {
if (cur > max) {
max = cur;
}
cur = 1;
}
}
return Math.max(cur, max);
};
/**
* @param {number[]} nums
* @return {number}
* score:94.51(54ms)
* time:O(n)
* space:O(n)
*/
var longestConsecutive2 = function (nums) {
let best = 0;
let s = new Set(nums);
for (let i of s) {
if (!s.has(i - 1)) {
let cur = i + 1;
while (s.has(cur)) {
cur++;
}
best = Math.max(best, cur - i);
}
}
return best;
}; |