Skip to content

Commit 4c42134

Browse files
committed
update
1 parent 7e4700f commit 4c42134

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

43. 最长连续序列.md

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
***给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。请你设计并实现时间复杂度为 O(n) 的算法解决此问题。***
2+
3+
Ref: https://leetcode.cn/problems/longest-consecutive-sequence/solution/zui-chang-lian-xu-xu-lie-by-leetcode-solution/
4+
![algo24](./images/algo24.jpg)
5+
6+
```
7+
class Solution:
8+
def longestConsecutive(self, nums: List[int]) -> int:
9+
longest_streak = 0
10+
num_set = set(nums)
11+
for num in num_set:
12+
if num - 1 not in num_set:
13+
current_num = num
14+
current_streak = 1
15+
while current_num + 1 in num_set:
16+
current_num += 1
17+
current_streak += 1
18+
longest_streak = max(longest_streak, current_streak)
19+
return longest_streak
20+
```

images/algo24.jpg

76.7 KB
Loading

0 commit comments

Comments
 (0)