当前位置:网站首页>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();
}
};
边栏推荐
- 数字图像隐写术之卡方分布
- Chi-square distribution of digital image steganography
- Word 表格跨页,仍然显示标题
- Parameter introduction and selection points of wireless module
- The client series of the DOM series
- 网站频繁出现mysql等数据库连接失败等信息解决办法
- 查看zabbix-release-5.0-1.el8.noarch.rpm包内容
- Installation problem corresponding to tensorflow and GPU version
- Responsive layout vs px/em/rem
- 16、注册中心-consul
猜你喜欢
无线模块的参数介绍和选型要点
Jiuzhou Cloud was selected into the "Trusted Cloud's Latest Evaluation System and the List of Enterprises Passing the Evaluation in 2022"
tensorflow与GPU版本对应安装问题
Problem record in the use of TypeScript
Sping.事务的传播特性
The Meta Metaverse Division lost 2.8 billion in the second quarter, still want to continue to bet?Metaverse development has yet to see a way out
typescript17 - function optional parameters
Ticmp - 更快的让应用从 MySQL 迁移到 TiDB
MySQL高级-六索引优化
ShardingSphere read-write separation (8)
随机推荐
想要写出好的测试用例,先要学会测试设计
typescript13 - type aliases
Typescript14 - (type) of the specified parameters and return values alone
打印任务排序 js od华为
小黑leetcode之旅:104. 二叉树的最大深度
Kyushu cloud as cloud computing standardization excellent member unit
Rocky/GNU之Zabbix部署(2)
设置浏览器滚动条样式
297. 二叉树的序列化与反序列化
The difference between 4G communication module CAT1 and CAT4
软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?
Sping.事务的传播特性
调度中心xxl-Job
PDF 拆分/合并
Rocky/GNU之Zabbix部署(1)
MySQL高级-六索引优化
Google官方控件ShapeableImageView使用
MySQL——数据库的查,增,删
《实战》基于情感词典的文本情感分析与LDA主题分析
Multiplication, DFS order