Skip to content

Commit 70639db

Browse files
committed
128. 最长连续序列
1 parent 942d853 commit 70639db

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
|122|[买卖股票的最佳时机 II](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/)|[JavaScript](./algorithms/best-time-to-buy-and-sell-stock-ii.js)|Medium|
8585
|124|[二叉树中的最大路径和](https://leetcode.cn/problems/binary-tree-maximum-path-sum/)|[JavaScript](./algorithms/binary-tree-maximum-path-sum.js)|Hard|
8686
|125|[验证回文串](https://leetcode.cn/problems/valid-palindrome/)|[JavaScript](./algorithms/valid-palindrome.js)|Easy|
87+
|128|[最长连续序列](https://leetcode.cn/problems/longest-consecutive-sequence/)|[JavaScript](./algorithms/longest-consecutive-sequence.js)|Medium|
8788
|129|[求根节点到叶节点数字之和](https://leetcode.cn/problems/sum-root-to-leaf-numbers/)|[JavaScript](./algorithms/sum-root-to-leaf-numbers.js)|Medium|
8889
|131|[分割回文串](https://leetcode.cn/problems/palindrome-partitioning/)|[JavaScript](./algorithms/palindrome-partitioning.js)|Medium|
8990
|134|[加油站](https://leetcode.cn/problems/gas-station/)|[JavaScript](./algorithms/gas-station.js)|Medium|
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function (nums) {
6+
// 时间复杂度: O(nlogn)
7+
// 空间复杂度: O(1)
8+
9+
if (nums.length <= 1) return nums.length;
10+
11+
nums.sort((a, b) => a - b);
12+
let maxLength = 1;
13+
let count = 1;
14+
15+
// 0 0 1 2 3 4 5 6 7 8
16+
17+
for (let i = 1; i < nums.length; i++) {
18+
if (nums[i] === nums[i - 1] + 1) {
19+
count++;
20+
} else if (nums[i] !== nums[i - 1]) {
21+
count = 1;
22+
}
23+
maxLength = Math.max(count, maxLength);
24+
}
25+
26+
return maxLength;
27+
};
28+
29+
// 时间复杂度: O(longn)
30+
// 空间复杂度: O(n)
31+
var longestConsecutive = function (nums) {
32+
// 题目要求时间复杂度为 O(n), 就用空间换时间
33+
// (一般在leetcode中,对时间复杂度有要求,就用空间来换,对空间复杂度有要求,就用时间来换)
34+
35+
const set = new Set(nums);
36+
let maxLength = 0;
37+
38+
for (let i = 0; i < nums.length; i++) {
39+
if (!set.has(nums[i] - 1)) {
40+
let val = nums[i];
41+
let curLen = 1;
42+
43+
while (set.has(val + 1)) {
44+
val++;
45+
curLen++;
46+
}
47+
maxLength = Math.max(curLen, maxLength);
48+
}
49+
}
50+
51+
return maxLength;
52+
};

0 commit comments

Comments
 (0)