File tree 2 files changed +53
-0
lines changed
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 84
84
| 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|
85
85
| 124| [ 二叉树中的最大路径和] ( https://leetcode.cn/problems/binary-tree-maximum-path-sum/ ) | [ JavaScript] ( ./algorithms/binary-tree-maximum-path-sum.js ) | Hard|
86
86
| 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|
87
88
| 129| [ 求根节点到叶节点数字之和] ( https://leetcode.cn/problems/sum-root-to-leaf-numbers/ ) | [ JavaScript] ( ./algorithms/sum-root-to-leaf-numbers.js ) | Medium|
88
89
| 131| [ 分割回文串] ( https://leetcode.cn/problems/palindrome-partitioning/ ) | [ JavaScript] ( ./algorithms/palindrome-partitioning.js ) | Medium|
89
90
| 134| [ 加油站] ( https://leetcode.cn/problems/gas-station/ ) | [ JavaScript] ( ./algorithms/gas-station.js ) | Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments