当前位置:网站首页>leetcode-128:最长连续序列
leetcode-128:最长连续序列
2022-07-31 01:33:00 【菊头蝙蝠】
题目
题目连接
给定一个未排序的整数数组 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
解题
方法一:哈希表
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> set;
for(int num:nums) set.insert(num);//去重
int res=0;
for(int num:set){
if(!set.count(num-1)){
//为了找到一个连续序列的起始位置
int cur_num=num;
int cur_count=1;
while(set.count(cur_num+1)){
cur_num++;
cur_count++;
}
res=max(res,cur_count);
}
}
return res;
}
};
方法二:并查集
class UnionFind{
private:
vector<int> parent;
vector<int> size;
public:
UnionFind(int n){
parent.resize(n);
size.resize(n);
for(int i=0;i<n;i++){
parent[i]=i;
size[i]=1;
}
}
int find(int index){
if(parent[index]==index) return index;
return parent[index]=find(parent[index]);
}
void unite(int index1,int index2){
int p1=find(index1);
int p2=find(index2);
if(p1!=p2){
parent[p1]=p2;
size[p2]+=size[p1];
}
}
int getMaxConn(){
int res=0;
for(int i=0;i<size.size();i++){
res=max(res,size[i]);
}
return res;
}
};
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int n=nums.size();
UnionFind uf(n);
unordered_map<int,int> mp;
for(int i=0;i<n;i++){
if(mp.count(nums[i])) continue;
if(mp.count(nums[i]-1)){
uf.unite(i,mp[nums[i]-1]);
}
if(mp.count(nums[i]+1)){
uf.unite(i,mp[nums[i]+1]);
}
mp[nums[i]]=i;
}
return uf.getMaxConn();
}
};
边栏推荐
- 1782. 统计点对的数目 双指针
- typescript9 - common base types
- 35. 反转链表
- 【Mysql】——索引的深度理解
- 822. Walk the Grid
- Installation problem corresponding to tensorflow and GPU version
- 力扣每日一题-第46天-704. 二分查找
- What have I experienced when I won the offer of BAT and TMD technical experts?
- Basic Parameters of RF Devices 2
- Can deep learning solve the parameters of a specific function?
猜你喜欢

35. 反转链表

297. 二叉树的序列化与反序列化

Can deep learning solve the parameters of a specific function?

35. Reverse linked list

Basic Parameters of RF Devices 1

TiCDC 架构和数据同步链路解析

The sword refers to offer17---print the n digits from 1 to the largest

This project is so geeky

九州云获评云计算标准化优秀成员单位

Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
随机推荐
typescript12 - union types
Dispatch Center xxl-Job
typescript15- (specify both parameter and return value types)
"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
Meta元宇宙部门第二季度亏损28亿 仍要继续押注?元宇宙发展尚未看到出路
Basic Parameters of RF Devices 2
Why use high-defense CDN when financial, government and enterprises are attacked?
华为od 转骰子 js
权限管理怎么做的?
MySQL的安装教程(嗷嗷详细,包教包会~)
【952. Calculate the maximum component size according to the common factor】
仿牛客网项目总结
基于Keras_bert模型的Bert使用与字词预测
系统设计.短链系统设计
87. 把字符串转换成整数
分布式.幂等性
Word/Excel 固定表格大小,填写内容时,表格不随单元格内容变化
Can deep learning solve the parameters of a specific function?
蛮力法/邻接表 广度优先 有向带权图 无向带权图
Jetpack Compose学习(8)——State及remeber