当前位置:网站首页>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;
}

边栏推荐
- Listener listener
- leetcode 1818 绝对值,排序,二分法,最大值
- Design of serial port receiving data scheme
- C language EXECL function
- GCC usage, makefile summary
- Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
- 监听器 Listener
- Go tool cli for command line implementation
- So easy 将程序部署到服务器
- 8 pits of redis distributed lock
猜你喜欢

8 pits of redis distributed lock

ctfshow爆破wp

终极套娃 2.0 | 云原生交付的封装
![[linear DP] longest common subsequence](/img/47/c3172422e997009facbada929adb1a.jpg)
[linear DP] longest common subsequence

Completely solve the lost connection to MySQL server at 'reading initial communication packet

Keil5中如何做到 0 Error(s), 0 Warning(s).

Feign远程调用和Getaway网关

Hal library operation STM32 serial port

Metadata in NFT

VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
随机推荐
Promise中finally的用法
The 'mental (tiring) process' of building kubernetes/kubesphere environment with kubekey
过滤器 Filter
# 使用 KubeKey 搭建 Kubernetes/KubeSphere 环境的'心路(累)历程'
第03章_用户与权限管理
手把手带你了解一块电路板,从设计到制作(干货)
8 pits of redis distributed lock
岭回归和lasso回归
Filter
How to verify whether the contents of two files are the same
pytorch训练深度学习网络设置cuda指定的GPU可见
力扣-两数之和
Druid监控统计数据源
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
File upload and download
Subnet division (10)
Feign远程调用和Getaway网关
[QT] add knowledge supplement of third-party database
How do I use Google Chrome 11's Upload Folder feature in my own code?
倍福TwinCAT3 Ads相关错误详细列表