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

边栏推荐
- 终极套娃 2.0 | 云原生交付的封装
- pytest-fixture
- Leetcode 1818 absolute value, sorting, dichotomy, maximum value
- 【日常训练】1175. 质数排列
- Introduction to ieda right click source file menu
- XXL job User Guide
- C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
- 【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
- 数据交换 JSON
- 家居网购项目
猜你喜欢

EDLines: A real-time line segment detector with a false detection control翻译

# 使用 KubeKey 搭建 Kubernetes/KubeSphere 环境的'心路(累)历程'

4、【WebGIS实战】软件操作篇——数据导入及处理
Common interview questions for performance test

How the network is connected: Chapter 2 (Part 2) packet receiving and sending operations between IP and Ethernet

E15 solution for cx5120 controlling Huichuan is620n servo error

第03章_用戶與權限管理

后台系统页面左边菜单按钮和右边内容的处理,后台系统页面出现双滚动

FCN全卷积网络理解及代码实现(来自pytorch官方实现)

Hal library operation STM32 serial port
随机推荐
家居网购项目
If a parent class defines a parameterless constructor, is it necessary to call super ()?
GCC usage, makefile summary
Keil5中如何做到 0 Error(s), 0 Warning(s).
数据库中COMMENT关键字的使用
Mybati SQL statement printing
How do spark tasks of 10W workers run? (Distributed Computing)
几行事务代码,让我赔了16万
完全背包问题
[us match preparation] complete introduction to word editing formula
EtherCAT简介
还在浪费脑细胞自学吗,这份面试笔记绝对是C站天花板
Nacos
实现pow(x,n)函数
How do I use Google Chrome 11's Upload Folder feature in my own code?
雪崩问题以及sentinel的使用
Server rendering technology JSP
Filter
XXL job User Guide
Common interview questions for performance test