Skip to content

Commit 2bbcc2c

Browse files
committed
[add] LeetCode 128. Longest Consecutive Sequence
1 parent 2399889 commit 2bbcc2c

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

algorithms-leetcode/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ Leetcode problems classified by company:
7171
|120|Triangle|Medium|||
7272
|121|Best Time to Buy and Sell Stock|Easy||待查最优解,以及一题多解|
7373
|122|Best Time to Buy and Sell Stock II|Medium|Dynamic Programming/Greedy|一题多解|
74+
|128|Longest Consecutive Sequence|Medium|Hash Table|TODO一题多解|
7475
|139|Word Break|Medium|Dynamic Programming,完全背包||
7576
|141|Linked List Cycle|Easy|Two Pointers||
7677
|144|Binary Tree Preorder Traversal|Easy|Binary Tree/Stack|一题多解|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}

0 commit comments

Comments
 (0)