algorighm/top-interview-leetcode150/hash-table/128数组中连续序列的最长长度.js

59 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* https://leetcode.cn/problems/longest-consecutive-sequence/?envType=study-plan-v2&envId=top-interview-150
* @param {number[]} nums
* @return {number}
*/
const longestConsecutive = function (nums) {
};
/*
思路题目所给的数组是无序的所以直接对数组排序依次遍历整个数组如果当前元素大于前一个元素并且等于前一个元素加1
把统计的长度加1如果不满足就比较是否比最大长度还大是的话就把这个长度作为为最大长度
*/
function f1(nums) {
nums.sort((a, b) => a - b);
if (nums.length === 0) return 0;
if (nums.length === 1) return 1;
let maxLen = 1; // 最大长度
let curLen = 1; // 统计长度
for (let i = 1; i < nums.length; i++) {
const preNum = nums[i - 1];
if (nums[i] === preNum) {
continue;
} else if (preNum + 1 === nums[i]) {
curLen++;
} else {
maxLen = Math.max(maxLen, curLen);
curLen = 1;
}
}
return Math.max(curLen, maxLen); // 如果后面一个很长的连续序列
}
/*
题目要求我们在O(n)的时间复杂度完成上面的做法使用了一次排序nlogn不符合要求正确的做法可以先用set对整个数组去重
整个过程的时间复杂度为O(n)之后遍历整个Set如果当前的num-1在set中不存在就表明这个num是数组中某个序列的开头开始统计
num+1在set中存在吗如果存在就计数加1如果不存在继续遍历
*/
function f2(nums) {
if (nums.length === 0) return 0;
const set = new Set(nums);
let maxLen = 1;
let curLen = 1;
for (const num of set) {
if (set.has(num - 1)) continue;
// 表明num是某个连续序列的开头直接开始统计
let next = num + 1;
while (set.has(next)) {
curLen++;
next++;
}
maxLen = Math.max(maxLen, curLen);
curLen = 1;
}
return maxLen;
}