首页 技术 正文
技术 2022年11月18日
0 收藏 315 点赞 3,103 浏览 1252 个字

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.

Your algorithm should run in O(n) complexity.

问题

给出一个未排序的整数数组,找出最长的连续元素序列的长度。

如:

给出[100, 4, 200, 1, 3, 2],

最长的连续元素序列是[1, 2, 3, 4]。返回它的长度:4。

你的算法必须有O(n)的时间复杂度 。

思路

  1. “排序转换成经典的动态规划问题”的话排序至少需要时间复杂度为O(nlog(n))——pass
  2. 利用c++中的set,直接会排序,并且没有重合的,但是set背后实现的原理牵扯到红黑树,时间复杂度不满足——pass
  3. 建立hash索引,把查找的元素周围的都访问个遍,求出个临时最大值跟全局最大值比较。当再次访问该段的元素的时候,直接跳过。这样保证时间复杂度为O(n),c++11中数据结构为unordered_set,保证查找元素的时间复杂度为O(1).

伪代码

最长连续序列(Longest Consecutive Sequence)

建立无序集合existSet visitedSet分别表示原集合中包含的元素和已经访问了的元素
全局最大个数maxLen
顺序遍历原集合中的元素
临时计数count=1
如果该元素在visitedSet,停止往下执行,进行下一次循环
否则,把改元素小的并且在existSet中的元素存放在visitedSet中,count++
把改元素大的并且在existSet中的元素存放在visitedSet中, count++
maxLen = max(maxLen, count)
 class Solution {
public:
int longestConsecutive(vector<int> &num) {
int max=;
std::unordered_set<int> visit;
std::unordered_set<int> exist;
for(int i=;i<num.size();i++){
exist.insert(num[i]);
}
for(int i=;i<num.size();i++){
if(visit.find(num[i])!=visit.end()){
continue;
}
int count=;
int left=num[i]-;
while(exist.find(left)!=exist.end()){
count++;
visit.insert(left);
left--;
}
int right=num[i]+;
while(exist.find(right)!=exist.end()){
count++;
visit.insert(right);
right++;
}
if(count>max)
max=count;
}
return max;
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919