@@ -53,7 +53,7 @@ return Math.max(count, maxCount);
5353
5454思路就是将之前”排序之后,通过比较前后元素是否相差 1 来判断是否连续“的思路改为
5555不排序而是` 直接遍历,然后在内部循环里面查找是否存在当前值的邻居元素 ` ,但是马上有一个
56- 问题,内部我们` 查找是否存在当前值的邻居元素 ` 的过程如果使用数组时间复杂度是 O(n),
56+ 问题,内部我们` 查找是否存在当前值的邻居元素 ` 的过程如果使用数组,时间复杂度是 O(n),
5757那么总体的复杂度就是 O(n^2),完全不可以接受。怎么办呢?
5858
5959我们换个思路,用空间来换时间。比如用类似于 hashmap 这样的数据结构优化查询部分,将时间复杂度降低到 O(1), 代码见后面` 代码部分 `
@@ -65,48 +65,20 @@ return Math.max(count, maxCount);
6565## 代码
6666
6767``` js
68- /*
69- * @lc app=leetcode id=128 lang=javascript
70- *
71- * [128] Longest Consecutive Sequence
72- *
73- * https://leetcode.com/problems/longest-consecutive-sequence/description/
74- *
75- * algorithms
76- * Hard (40.98%)
77- * Total Accepted: 200.3K
78- * Total Submissions: 484.5K
79- * Testcase Example: '[100,4,200,1,3,2]'
80- *
81- * Given an unsorted array of integers, find the length of the longest
82- * consecutive elements sequence.
83- *
84- * Your algorithm should run in O(n) complexity.
85- *
86- * Example:
87- *
88- *
89- * Input: [100, 4, 200, 1, 3, 2]
90- * Output: 4
91- * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4].
92- * Therefore its length is 4.
93- *
94- *
95- */
9668/**
9769 * @param {number[]} nums
9870 * @return {number}
9971 */
10072var longestConsecutive = function (nums ) {
101- nums = new Set (nums);
73+ set = new Set (nums);
10274 let max = 0 ;
103- let y = 0 ;
104- nums .forEach (x => {
75+ let temp = 0 ;
76+ set .forEach (x => {
10577 // 说明x是连续序列的开头元素
106- if (! nums .has (x - 1 )) {
107- y = x + 1 ;
108- while (nums .has (y)) {
109- y = y + 1 ;
78+ if (! set .has (x - 1 )) {
79+ temp = x + 1 ;
80+ while (set .has (y)) {
81+ temp = temp + 1 ;
11082 }
11183 max = Math .max (max, y - x); // y - x 就是从x开始到最后有多少连续的数字
11284 }
0 commit comments