当前位置:网站首页>LeetCode 128最长连续序列(哈希set)
LeetCode 128最长连续序列(哈希set)
2022-07-01 03:15:00 【是七叔呀】
Top1:LeetCode 128最长连续序列(哈希set)【数组中可以有重复数字,大那是会用set去重不影响】
题目描述:
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
一、考虑枚举数组存到set后for(int num : set)遍历,从每一个x开始枚举set中是否contains(x+1)记录长度;但是这里要去重,即当遍历x存在x-1在set中时,跳过
二、使用一个current存储遍历到的当前num的流长,再longest = Math.max(longest, current);存储最长答案
去重跳过细节参考leetcode源网页中的幻灯片图:最长连续序列-哈希表
这里将数组存到set和遍历代码:
Set<Integer> set = new HashSet<>();
for (int num : nums) {
// 去重,且查询在不在的时间复杂度为O(1)
set.add(num);
}
int longest = 0; // 初始化最终返回值,进入for循环后会longest = Math.max(longest, current);更新
for (int num : set) {
} // 遍历set哈希集合 // for循环中的每一个num都是新的,和上一次的num不冲突,类似于局部变量
可通过完整代码
public static int longestConsecutive2(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
// 去重,且查询在不在的时间复杂度为O(1)
set.add(num);
}
int longest = 0; // 初始化最终返回值,进入for循环后会longest = Math.max(longest, current);更新
for (int num : set) {
// 遍历set哈希集合 // for循环中的每一个num都是新的,和上一次的num不冲突,类似于局部变量
if (!set.contains(num - 1)) {
// int curNum = num; // 存储当前num,进入后面的while循环
int current = 1; // 给num流长度变为1
while (set.contains(num + 1)) {
num += 1;
current += 1;
}
longest = Math.max(longest, current);
}
}
return longest;
}

边栏推荐
- Learning notes for introduction to C language multithreaded programming
- pytest-fixture
- MySQL knowledge points
- Introduction to the core functions of webrtc -- an article to understand peerconnectionfactoryinterface rtcconfiguration peerconnectioninterface
- Latest interface automation interview questions
- 服务器渲染技术jsp
- Druid监控统计数据源
- FCN全卷积网络理解及代码实现(来自pytorch官方实现)
- Redis tutorial
- HTB-Lame
猜你喜欢
随机推荐
Stop saying that you can't solve the "cross domain" problem
Golang multi graph generation gif
Ultimate dolls 2.0 | encapsulation of cloud native delivery
[us match preparation] complete introduction to word editing formula
C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
The best learning method in the world: Feynman learning method
【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
leetcode 1818 绝对值,排序,二分法,最大值
Design practice of current limiting components
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
限流组件设计实战
Basic concept and classification of sorting
The 'mental (tiring) process' of building kubernetes/kubesphere environment with kubekey
Best used trust automation script (shell)
JS日常开发小技巧(持续更新)
C language EXECL function
Edge Drawing: A combined real-time edge and segment detector 翻译
Leetcode 1482 guess, how about this question?
Leetcode 1818 absolute value, sorting, dichotomy, maximum value
实战 ELK 优雅管理服务器日志









