当前位置:网站首页>leetcode-128: longest continuous sequence
leetcode-128: longest continuous sequence
2022-07-31 01:44:00 【chrysanthemum bat】
题目
题目连接
给定一个未排序的整数数组 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)){
//To find the starting position of a contiguous sequence
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();
}
};
边栏推荐
猜你喜欢

Are you still working hard on the limit of MySQL paging?

MySQL installation tutorial (detailed, package teaching package~)

35. Reverse linked list

Fiddler抓包模拟弱网络环境测试

RTL8720DN开发笔记一 环境搭建与mqtt实例

软件测试报告有哪些内容?

ROS Action communication

Kyushu cloud as cloud computing standardization excellent member unit

基于Keras_bert模型的Bert使用与字词预测

Parameter introduction and selection points of wireless module
随机推荐
Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
leetcode-128:最长连续序列
C语言_结构体指针数组函数选票系统
类似 MS Project 的项目管理工具有哪些
观察者(observer)模式(一)
《实战》基于电商领域的词性提取及其决策树模型建模
MySQL的分页你还在使劲的limit?
计算S=a+aa+…+aa…a
What have I experienced when I won the offer of BAT and TMD technical experts?
Interprocess communication study notes
TiCDC 架构和数据同步链路解析
kotlin中函数作为参数和函数作为返回值实例练习
1782. 统计点对的数目 双指针
Parameter introduction and selection points of wireless module
初识C语言 -- 数组
MySQL的安装教程(嗷嗷详细,包教包会~)
Shell变量与赋值、变量运算、特殊变量
Are you still working hard on the limit of MySQL paging?
"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
The difference between 4G communication module CAT1 and CAT4