当前位置:网站首页>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?
- 最高月薪20K?平均薪资近万...在华为子公司工作是什么体验?
- 【Mysql】——索引的深度理解
- Charging effect simulation
- 软件测试基础接口测试-入门Jmeter,你要注意这些事
- 观察者(observer)模式(一)
- 什么是理想的大学生活?
- The sword refers to offer17---print the n digits from 1 to the largest
- 《实战》基于电商领域的词性提取及其决策树模型建模
猜你喜欢

Distributed. Idempotency

Xiaohei's leetcode journey: 104. The maximum depth of a binary tree

Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II

MySQL installation tutorial (detailed, package teaching package~)

软件测试要达到一个什么水平才能找到一份9K的工作?

Shell变量与赋值、变量运算、特殊变量

数字图像隐写术之卡方分布

汉诺塔问题

进程间通信学习笔记

【flask入门系列】Flask-SQLAlchemy的使用
随机推荐
Gateway路由的配置方式
87. Convert String to Integer
MySQL installation tutorial (detailed, package teaching package~)
tensorflow与GPU版本对应安装问题
有没有可以做副业可以日入300元方法?
[Map and Set] LeetCode & Niu Ke exercise
221. 最大正方形
Know what DTU is 4GDTU equipment
Centos 7.9安装PostgreSQL14.4步骤
What is the ideal college life?
加密生活,Web3 项目合伙人的一天
Programmer's debriefing report/summary
leetcode-128:最长连续序列
RTL8720DN开发笔记一 环境搭建与mqtt实例
MySql installation and configuration super detailed tutorial and simple method of building database and table
leetcode-1161:最大层内元素和
tkinter模块高级操作(二)—— 界面切换效果、立体阴影字效果及gif动图的实现
Crawler text data cleaning
Installation problem corresponding to tensorflow and GPU version
prometheus 监控概述