当前位置:网站首页>Leetcode刷题——128. 最长连续序列
Leetcode刷题——128. 最长连续序列
2022-08-03 05:20:00 【lonelyMangoo】
题目
思路
遍历数组,用map集合记录已经遍历的数。
key表示当前数,value表示该数所在序列的长度。
有当key值不在map中时(防止重复),进行如下操作,假设当前值是num:
- 当num-1存在时,记录map中num-1的值left
- 当num+1存在时,记录map中num+1的值right
- 所以当前的长度就是left+right+1。
- 判断并保留最大值。
- 关键一步:将另外两个边界设为和第三步中一样,这样边界都确定了。并且由于循环中不会去找已经在map中存在的,所以避免了重复的情况的发生。
代码
public static int longestConsecutive(int[] nums) {
Map<Integer, Integer> map = new HashMap<>(nums.length);
int max = 0;
for (int num : nums) {
int left = 0;
int right = 0;
if (!map.containsKey(num)) {
if (map.containsKey(num - 1)) {
left = map.get(num - 1);
}
if (map.containsKey(num + 1)) {
right = map.get(num + 1);
}
int nowLen = left + right + 1;
if (nowLen > max) {
max = nowLen;
}
//这一片都处理过了
map.put(num-left,nowLen);
map.put(num+right,nowLen);
map.put(num, nowLen);
}
}
return max;
}

边栏推荐
猜你喜欢
随机推荐
docker mysql 容器中执行mysql脚本文件并解决乱码
陆运信息系统——班列项目总结(一)
小码农的第一篇博客
Go (一) 基础部分3 -- 数组,切片(append,copy),map,指针
OptionError: ‘Pattern matched multiple keys‘
令人愉快的 Nuxt3 教程 (一): 应用的创建与配置
【frp内网穿透】
[Rebound shell and privilege escalation]
第四次培训
关于如何向FastAPI的依赖函数添加参数
7.18(7)
【Arduino】关于“&”和“|” 运算-----多个参数运算结果异常的问题解决
-钞票兑换-
一维数组和二维数组的命名以及存储空间
Sqli-labs-master shooting range 1-23 customs clearance detailed tutorial (basic)
用C语言来实现五子棋小游戏
编写一个函数 reverse_string(char * string)(两种方法实现)7.26
【转】最小描述长度准则MDL(Minimun Description Length)
【DC-2靶场渗透】
轨迹(形状)相似性判断与度量方法






![二叉树的合并[C]](/img/c2/08535044681dd477c0028b4306b77e.png)

![7.24[C语言零基础 知识点总结]](/img/b8/3abcee495e70c9ffffc671f2b7d9b1.png)
