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

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

这道题要求求最长连续序列,并给定了O(n)复杂度限制,我们的思路是,使用一个集合HashSet存入所有的数字,然后遍历数组中的每个数字,如果其在集合中存在,那么将其移除,然后分别用两个变量pre和next算出其前一个数跟后一个数,然后在集合中循环查找,如果pre在集合中,那么将pre移除集合,然后pre再自减1,直至pre不在集合之中,对next采用同样的方法,那么next-pre-1就是当前数字的最长连续序列,更新res即可。这里再说下,为啥当检测某数字在集合中存在当时候,都要移除数字。这是为了避免大量的重复计算,就拿题目中的例子来说吧,我们在遍历到4的时候,会向下遍历3,2,1,如果都不移除数字的话,遍历到1的时候,还会遍历2,3,4。同样,遍历到3的时候,向上遍历4,向下遍历2,1,等等等。如果数组中有大量的连续数字的话,那么就有大量的重复计算,十分的不高效,所以我们要从HashSet中移除数字,代码如下:

C++ 解法一:

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int res = ;
unordered_set<int> s(nums.begin(), nums.end());
for (int val : nums) {
if (!s.count(val)) continue;
s.erase(val);
int pre = val - , next = val + ;
while (s.count(pre)) s.erase(pre--);
while (s.count(next)) s.erase(next++);
res = max(res, next - pre - );
}
return res;
}
};

Java 解法一:

public class Solution {
public int longestConsecutive(int[] nums) {
int res = ;
Set<Integer> s = new HashSet<Integer>();
for (int num : nums) s.add(num);
for (int num : nums) {
if (s.remove(num)) {
int pre = num - , next = num + ;
while (s.remove(pre)) --pre;
while (s.remove(next)) ++next;
res = Math.max(res, next - pre - );
}
}
return res;
}
}

我们也可以采用哈希表来做,刚开始HashMap为空,然后遍历所有数字,如果该数字不在HashMap中,那么我们分别看其左右两个数字是否在HashMap中,如果在,则返回其哈希表中映射值,若不在,则返回0,虽然我们直接从HashMap中取不存在的映射值,也能取到0,但是一旦去取了,就会自动生成一个为0的映射,那么我们这里再for循环的开头判断如果存在映射就跳过的话,就会出错。然后我们将left+right+1作为当前数字的映射,并更新res结果,同时更新num-left和num-right的映射值。

下面来解释一下为啥要判断如何存在映射的时候要跳过,这是因为一旦某个数字创建映射了,说明该数字已经被处理过了,那么其周围的数字很可能也已经建立好了映射了,如果再遇到之前处理过的数字,再取相邻数字的映射值累加的话,会出错。举个例子,比如数组 [1, 2, 0, 1],当0执行完以后,HashMap中的映射为 {1->2, 2->3, 0->3},可以看出此时0和2的映射值都已经为3了,那么如果最后一个1还按照原来的方法处理,随后得到结果就是7,明显不合题意。还有就是,之前说的,为了避免访问不存在的映射值时,自动创建映射,我们使用m.count() 先来检测一下,只有存在映射,我们才从中取值,否则就直接赋值为0,参见代码如下:

C++ 解法二:

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int res = ;
unordered_map<int, int> m;
for (int num : nums) {
if (m.count(num)) continue;
int left = m.count(num - ) ? m[num - ] : ;
int right = m.count(num + ) ? m[num + ] : ;
int sum = left + right + ;
m[num] = sum;
res = max(res, sum);
m[num - left] = sum;
m[num + right] = sum;
}
return res;
}
};

Java 解法二:

public class Solution {
public int longestConsecutive(int[] nums) {
int res = 0;
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int num : nums) {
if (m.containsKey(num)) continue;
int left = m.containsKey(num - 1) ? m.get(num - 1) : 0;
int right = m.containsKey(num + 1) ? m.get(num + 1) : 0;
int sum = left + right + 1;
m.put(num, sum);
res = Math.max(res, sum);
m.put(num - left, sum);
m.put(num + right, sum);
}
return res;
}
}

类似题目:

Binary Tree Longest Consecutive Sequence

参考资料:

https://leetcode.com/problems/longest-consecutive-sequence/

https://leetcode.com/problems/longest-consecutive-sequence/discuss/41055/my-really-simple-java-on-solution-accepted

https://leetcode.com/problems/longest-consecutive-sequence/discuss/41060/a-simple-csolution-using-unordered_setand-simple-consideration-about-this-problem

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Longest Consecutive Sequence 求最长连续序列的更多相关文章

  1. [LeetCode] 128. Longest Consecutive Sequence 求最长连续序列

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

  2. [LintCode] Longest Consecutive Sequence 求最长连续序列

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

  3. [LeetCode] 298. Binary Tree Longest Consecutive Sequence 二叉树最长连续序列

    Given a binary tree, find the length of the longest consecutive sequence path. The path refers to an ...

  4. [LeetCode] Binary Tree Longest Consecutive Sequence 二叉树最长连续序列

    Given a binary tree, find the length of the longest consecutive sequence path. The path refers to an ...

  5. LeetCode--Longest Consecutive Sequence(最长连续序列) Python

    题目描述: Longest Consecutive Sequence(最长连续序列) 中文: 给定一个未排序的整数数组,找出最长连续序列的长度. 要求算法的时间复杂度为 O(n). 英文: Given ...

  6. LeetCode——Longest Consecutive Sequence

    LeetCode--Longest Consecutive Sequence Question Given an unsorted array of integers, find the length ...

  7. LeetCode: Longest Consecutive Sequence 解题报告

    Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longest con ...

  8. [Leetcode] Longest Consecutive Sequence 略详细 (Java)

    题目参见这里 https://leetcode.com/problems/longest-consecutive-sequence/ 这个题目我感觉很难,看了半天别人写的答案,才明白个所以然.下面的代 ...

  9. leetcode.哈希表.128最长连续序列-Java

    1. 具体题目 给定一个未排序的整数数组,找出最长连续序列的长度.要求算法的时间复杂度为 O(n). 示例: 输入: [100, 4, 200, 1, 3, 2] 输出: 4 解释: 最长连续序列是 ...

随机推荐

  1. 行为驱动开发(BDD)实践示例

    引言 BDD是对TDD理念的扩展.BDD强调有利害关系的技术团体和非技术团队都要参与到软件开发过程中.可以把它看成一种强调团体间合作的敏捷方法.大多数采用某种敏捷方法的团队最终都会遵循BDD的许多原则 ...

  2. CloudNotes之桌面客户端篇:笔记撰写样式的支持

    最近在CloudNotes桌面客户端中新增了笔记撰写样式的功能.当用户新建笔记的时候,可以在输入笔记标题的同时,选择笔记撰写样式,由安装包默认提供的样式主要有默认样式(Default).羊皮纸样式(L ...

  3. 初识ASP.NET MVC

    我们首先从创建ASP.NET MVC项目开始.打开Visual Studio,在文件菜单中选择新建-> 项目,然后在模板中选择Web,接着选择ASP.Net Web应用程序,更改项目名称,点击确 ...

  4. 查看Sql Server被锁的表以及解锁

    查看被锁表: select spId from master..SysProcesses where db_Name(dbID) = '数据库名称' and spId <> @@SpId ...

  5. Struts+Spring+Hibernate项目的启动线程

    在Java Web项目中,经常要在项目开始运行时启动一个线程,每隔一定的时间就运行一定的代码,比如扫描数据库的变化等等.要实现这个功能,可以现在web.xml文件中定义一个Listener,然后在这个 ...

  6. apache.commons.io.IOUtils: 一个很方便的IO工具库(比如InputStream转String)

    转换InputStream到String, 比如 //引入apache的io包 import org.apache.commons.io.IOUtils; ... ...String str = IO ...

  7. 经典的一款jQuery soChange幻灯片

    soChange一款多很经典的幻灯片的jQuery插件. 实例预览 引入文件 <link rel="stylesheet" type="text/css" ...

  8. 如何写出高质量的技术博客 这边文章出自http://www.jianshu.com/p/ae9ab21a5730 觉得不错直接拿过来了 好东西要大家分享嘛

        如何写出高质量的技术博客?答案是:如果你想,就一定能写出高质量的技术博客.看起来很唯心,但这就是事实.有足够愿力去做一件目标明确,有良好反馈系统的事情往往很简单.就是不停地训练,慢慢地,你自己 ...

  9. 一个基于Microsoft Azure、ASP.NET Core和Docker的博客系统

    2008年11月,我在博客园开通了个人帐号,并在博客园发表了自己的第一篇博客.当然,我写博客也不是从2008年才开始的,在更早时候,也在CSDN和系统分析员协会(之后名为“希赛网”)个人空间发布过一些 ...

  10. 突然想到一个问题:有关 cqrs 分离

    大部分的系统,都是查询多,c少,那为什么我们不把q放在内存里面,而c直接操作数据库呢? 就如enode,c在内存,而q在数据库,当然q也很容易扩展到内存缓存上.二个enode案例demo,都可以让c的 ...