File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
src/main/java/com/brianway/learning/algorithms/leetcode/medium Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -71,6 +71,7 @@ Leetcode problems classified by company:
71
71
| 120| Triangle| Medium|||
72
72
| 121| Best Time to Buy and Sell Stock| Easy|| 待查最优解,以及一题多解|
73
73
| 122| Best Time to Buy and Sell Stock II| Medium| Dynamic Programming/Greedy| 一题多解|
74
+ | 128| Longest Consecutive Sequence| Medium| Hash Table| TODO一题多解|
74
75
| 139| Word Break| Medium| Dynamic Programming,完全背包||
75
76
| 141| Linked List Cycle| Easy| Two Pointers||
76
77
| 144| Binary Tree Preorder Traversal| Easy| Binary Tree/Stack| 一题多解|
Original file line number Diff line number Diff line change
1
+ package com .brianway .learning .algorithms .leetcode .medium ;
2
+
3
+ import java .util .HashSet ;
4
+
5
+ /**
6
+ * LeetCode 128. Longest Consecutive Sequence
7
+ * Question: https://leetcode.com/problems/longest-consecutive-sequence/
8
+ * 关键题设:runs in O(n) time.
9
+ *
10
+ * @auther brian
11
+ * @since 2022/9/6 23:59
12
+ */
13
+ public class LongestConsecutiveSequence {
14
+ public int longestConsecutive (int [] nums ) {
15
+ return 0 ;
16
+ }
17
+
18
+ /**
19
+ * 哈希表
20
+ * <p>
21
+ * 先构建哈希集合,用于去重;
22
+ * 再依次遍历其中的元素num:只统计num-1不在其中时,一直next,看nums++是否在哈希集合中,统计next的次数
23
+ * 1)如果num-1在里面,则忽略跳过
24
+ * 2)如果num-1不在里面,则每次查看看num是否在里面
25
+ *
26
+ * <p>
27
+ * 时间复杂度:O(n)
28
+ * 空间复杂度:O(n)
29
+ */
30
+ public class LongestConsecutiveSequence0 extends LongestConsecutiveSequence {
31
+ @ Override
32
+ public int longestConsecutive (int [] nums ) {
33
+ // 构建哈希Set
34
+ HashSet <Integer > hashSet = new HashSet <>();
35
+ for (int i = 0 ; i < nums .length ; i ++) {
36
+ hashSet .add (nums [i ]);
37
+ }
38
+ int maxCount = 0 ;
39
+ // 遍历
40
+ for (int num : hashSet ) {
41
+ if (!hashSet .contains (num - 1 )) {
42
+ // 进入统计循环
43
+ int curCount = 1 ;
44
+ int cur = num ;
45
+ while (hashSet .contains (++cur )) {
46
+ curCount ++;
47
+ }
48
+ maxCount = Math .max (maxCount , curCount );
49
+ }
50
+ // else 忽略
51
+ }
52
+ return maxCount ;
53
+ }
54
+ }
55
+
56
+ // TODO 其他解法
57
+ }
You can’t perform that action at this time.
0 commit comments