File tree Expand file tree Collapse file tree 3 files changed +73
-0
lines changed Expand file tree Collapse file tree 3 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 56
56
122. 买卖股票的最佳时机 II
57
57
123. 买卖股票的最佳时机 III
58
58
124. 二叉树中的最大路径和
59
+ 128. 最长连续序列
59
60
129. 求根节点到叶节点数字之和
60
61
130. 被围绕的区域
61
62
131. 分割回文串
Original file line number Diff line number Diff line change 147
147
56. 合并区间
148
148
75. 颜色分类
149
149
88. 合并两个有序数组
150
+ 128. 最长连续序列
150
151
136. 只出现一次的数字
151
152
169. 多数元素
152
153
215. 数组中的第K个最大元素
Original file line number Diff line number Diff line change
1
+ // 128. 最长连续序列
2
+
3
+
4
+ /*
5
+ 集合:
6
+ 1、集合存放去重元素
7
+ 2、遍历元素
8
+ 1)元素前值存在集合中则跳过,因为当前元素会被前值计算统计出更长的长度,即只从序列的起点开始计算才是最长的
9
+ 2)记录当前元素和当前长度,当元素后值存在集合中,则更新当前元素和当前长度
10
+ 3)比较比记录最长长度
11
+ 4)优化,最长长度大于数组长度一半时,后面的元素就不用判断了
12
+ 因为如果剩余元素不属于这个序列那么长度小于数组长度一半
13
+ 如果属于这个序列,那么序列起点已经计算了,当前就是最长了
14
+
15
+ √:计算长度 x:跳过
16
+ 100 4 200 1 3 2
17
+ √ x √ √ x x
18
+ */
19
+ class Solution {
20
+ public int longestConsecutive (int [] nums ) {
21
+ Set <Integer > set = new HashSet <>();
22
+ for (int num : nums ) {
23
+ set .add (num );
24
+ }
25
+ int res = 0 ;
26
+ for (int num : nums ) {
27
+ if (set .contains (num - 1 )) {
28
+ continue ;
29
+ }
30
+ int curNum = num ;
31
+ int curLen = 1 ;
32
+ while (set .contains (curNum + 1 )) {
33
+ curNum += 1 ;
34
+ curLen += 1 ;
35
+ }
36
+ res = Math .max (res , curLen );
37
+ if (res > n / 2 ) {
38
+ break ;
39
+ }
40
+ }
41
+ return res ;
42
+ }
43
+ }
44
+
45
+
46
+ /*
47
+ 排序:
48
+ 1、数组排序
49
+ 2、遍历统计连续序列长度,记录最长长度
50
+ */
51
+ class Solution {
52
+ public int longestConsecutive (int [] nums ) {
53
+ Arrays .sort (nums );
54
+ int n = nums .length ;
55
+ if (n < 2 ) {
56
+ return n ;
57
+ }
58
+ int res = 1 , curLen = 1 ;
59
+ for (int i = 1 ; i < n ; i ++) {
60
+ if (nums [i ] == nums [i - 1 ] + 1 ) {
61
+ curLen += 1 ;
62
+ res = Math .max (res , curLen );
63
+ } else if (nums [i ] == nums [i - 1 ]) {
64
+ continue ;
65
+ } else {
66
+ curLen = 1 ;
67
+ }
68
+ }
69
+ return res ;
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments