当前位置:网站首页>【LeetCode】128. 最长连续序列
【LeetCode】128. 最长连续序列
2022-06-10 01:08:00 【LawsonAbs】
0.总结
- 如果想降低时间复杂度,那么可能就要使用大内存(提升空间复杂度)。
- 【一串序列只会有一个起点】
1.题目
2.思想
这题还挺难想的。难点在于,如何保证是O(n)的时间复杂度?我们可以设置一个字典用于存储list出现过的数字。当遇到一个数字num的时候,可能其是一串序列的一个数字,也可能是一个单独的数字。【但是我们知道一串序列只会有一个起点】,所以如果该数-1 (num-1)在集合中,那么直接跳过该数,因为它不是本串序列的起点。如果不在集合中,那么赋值res=1。
具体地说:
- (1)定义一个set集合。用于表示当前这个list存在的数
- (2)顺序遍历list中的数,同时判断num-1( num=nums[i]) 是否在set中,如果在,那么就continue到下一个,否则判断 num+1 是否在set中,更新结果
3.代码
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
a = set(nums)
res = 0
for i in range(len(nums)):
cur_num = nums[i]
if cur_num - 1 in a: # 如果num-1也存在这个list中,那么就直接continue
continue
else: # 开始顺序搜索
cnt = 0
while(cur_num in a):
cnt+=1
cur_num+=1
res = max(res,cnt)
return res
边栏推荐
- Benders Decomposition study notes
- Associative array & regular expression
- 项目成功了,最大的功臣居然是项目经理?
- LEAK: ByteBuf. release() was not called before it‘s garbage-collected
- Picture batch download + picture mosaic: multiple pictures constitute the Dragon Boat Festival Ankang!
- 分布式数据库下子查询和 Join 等复杂 SQL 如何实现?
- [Multisim Simulation] differential proportional amplifier circuit
- Locust: a powerful tool for microservice performance testing
- More powerful reduce than you think and thinking about code tapping
- Unity技术 - 2D项目经验
猜你喜欢

Alleviate and repair Android studio Caton, kotlin code prompt is slow

Batch downloading of pictures + mosaic of pictures: multiple pictures constitute the Dragon Boat Festival Ankang

Two problems of DataGrid

【Multisim仿真】差分比例放大电路

0 is it feasible to conduct software testing only by self-study? After reading this article, I am not confused

Domain Adaptation and Graph Neural Networks

MySQL -- how to solve the problem of data read consistency

RHCSA第七天

Win11怎么直接退回进入桌面?

How to implement complex SQL such as distributed database sub query and join?
随机推荐
datagrip的两个问题
MySQL - separate database and table
LEAK: ByteBuf.release() was not called before it‘s garbage-collected
MySQL - transaction attributes
MySQL -- how to solve the problem of data read consistency
为什么程序员干两年就跑路?
亚洲首屈一指的Web3盛事“TOKEN2049新加坡”公布冠名赞助商
电脑系统怎么修改图片格式
Way home
Locust: a powerful tool for microservice performance testing
[HFCTF2020]BabyUpload
Mysql——》varchar
Rhcsa day 7
Reprint the Alibaba open source project egg JS technical documents cause "copyright disputes". How to use the loose MIT license?
PCI bar register explanation (I)
国内现货白银有哪些好技术:常见指标的简单用法
Curriculum Learning and Graph Neural Networks (or Graph Structure Learning)
ESRI integrates Lightbox data to extend geocoding in Canada
How can win11 directly return to the desktop?
The state of gurobi solution and its attribute acquisition