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.

给一个非排序的整数数组,找出最长连续序列的长度。要求时间复杂度:O(n)。

解法1:要O(n)复杂度,排序显然不行,要用hash table。将序列中的所有数存到一个unordered_set中。对于序列里任意一个数A[i],可以通过set马上能知道A[i]+1和A[i]-1是否也在序列中。如果在,继续找A[i]+2和A[i]-2,以此类推,直到将整个连续序列找到。为了避免在扫描到A[i]-1时再次重复搜索该序列,在从每次搜索的同时将搜索到的数从set中删除。直到set中为空时,所有连续序列搜索结束。

解法2: 参考自:StefanPochmann

First turn the input into a set of numbers. That takes O(n) and then we can ask in O(1) whether we have a certain number.Then go through the numbers. If the number x is the start of a streak (i.e., x-1 is not in the set), then test y = x+1, x+2, x+3, ... and stop at the first number y not in the set. The length of the streak is then simply y-x and we update our global best with that. Since we check each streak only once, this is overall O(n). This ran in 44 ms on the OJ, one of the fastest Python submissions.

其它参考:GeeksforGeeks

1) Create an empty hash.
2) Insert all array elements to hash.
3) Do following for every element arr[i]
  a) Check if this element is the starting point of a subsequence. To check this, we simply look forarr[i] - 1 in hash, if not found, then this is the first element a subsequence.
If this element is a first element, then count number of elements in the consecutive starting with this element.

If count is more than current res, then update res.

Java:

class Solution {
public static int longestConsecutive(int[] num) {
// if array is empty, return 0
if (num.length == 0) {
return 0;
} Set<Integer> set = new HashSet<Integer>();
int max = 1; for (int e : num)
set.add(e); for (int e : num) {
int left = e - 1;
int right = e + 1;
int count = 1; while (set.contains(left)) {
count++;
set.remove(left);
left--;
} while (set.contains(right)) {
count++;
set.remove(right);
right++;
} max = Math.max(count, max);
} return max;
}
}  

Java:

public int longestConsecutive(int[] num) {
int res = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int n : num) {
if (!map.containsKey(n)) {
int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0;
int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0;
// sum: length of the sequence n is in
int sum = left + right + 1;
map.put(n, sum); // keep track of the max length
res = Math.max(res, sum); // extend the length to the boundary(s)
// of the sequence
// will do nothing if n has no neighbors
map.put(n - left, sum);
map.put(n + right, sum);
}
else {
// duplicates
continue;
}
}
return res;
}  

Java:

public int longestConsecutive(int[] nums) {
Map<Integer,Integer> ranges = new HashMap<>();
int max = 0;
for (int num : nums) {
if (ranges.containsKey(num)) continue; // 1.Find left and right num
int left = ranges.getOrDefault(num - 1, 0);
int right = ranges.getOrDefault(num + 1, 0);
int sum = left + right + 1;
max = Math.max(max, sum); // 2.Union by only updating boundary
// Leave middle k-v dirty to avoid cascading update
if (left > 0) ranges.put(num - left, sum);
if (right > 0) ranges.put(num + right, sum);
ranges.put(num, sum); // Keep each number in Map to de-duplicate
}
return max;
} 

Java: 2

public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int n : nums) {
set.add(n);
}
int best = 0;
for(int n : set) {
if(!set.contains(n - 1)) { // only check for one direction
int m = n + 1;
while(set.contains(m)) {
m++;
}
best = Math.max(best, m - n);
}
}
return best;
}  

Python:

class Solution:
# @param num, a list of integer
# @return an integer
def longestConsecutive(self, num):
result, lengths = 1, {key: 0 for key in num}
for i in num:
if lengths[i] == 0:
lengths[i] = 1
left, right = lengths.get(i - 1, 0), lengths.get(i + 1, 0)
length = 1 + left + right
result, lengths[i - left], lengths[i + right] = max(result, length), length, length
return result

Python: 2

def longestConsecutive(self, nums):
nums = set(nums)
best = 0
for x in nums:
if x - 1 not in nums:
y = x + 1
while y in nums:
y += 1
best = max(best, y - x)
return best  

C++:

class Solution {
public:
int longestConsecutive(vector<int> &num) {
if(num.empty()) return 0;
unordered_set<int> ht;
for(int i=0; i<num.size(); i++)
ht.insert(num[i]); int maxLen = 1;
for(int i=0; i<num.size(); i++) {
if(ht.empty()) break;
int curLen = 0;
int curNum = num[i]; while(ht.count(curNum)) {
ht.erase(curNum);
curLen++;
curNum++;
} curNum = num[i]-1;
while(ht.count(curNum)) {
ht.erase(curNum);
curLen++;
curNum--;
} maxLen = max(maxLen, curLen);
} return maxLen;
}
};

 

类似题目:

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

All LeetCode Questions List 题目汇总

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

  1. [LeetCode] 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]128. Longest Consecutive Sequence最长连续序列

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

  7. LeetCode 128 Longest Consecutive Sequence 一个无序整数数组中找到最长连续序列

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

  8. [LeetCode] 128. Longest Consecutive Sequence 解题思路

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

  9. leetcode 128. Longest Consecutive Sequence ----- java

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

随机推荐

  1. Linux 文件监控之谁动了我的奶酪

    有时候配置文件会被莫名其妙的修改,但是找不到修改他的进程,从而无法抓住罪魁祸首,这时候就诞生了摄像头.呃呃,应该是audit 比如我要监控一个文件test.txt [root@hsun /]# aud ...

  2. python爬虫中的ip代理设置

    设置ip代理是爬虫必不可少的技巧: 查看本机ip地址:打开百度,输入“ip地址”,可以看到本机的IP地址: 本文使用的是goubanjia.com里面的免费ip: 使用时注意要注意传输协议是http还 ...

  3. 《BUG创造队》第九次团队作业:Beta冲刺与验收准备

    项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验十三 团队作业9:Beta冲刺与团队项目验收 团队名称 BUG创造队 作业学习目标 (1)掌握软件黑盒测试技术:(2)学 ...

  4. mysql数据库的concat(),group_concat(),concat_ws()函数,三者之间的比较

    今天在写项目的时候,看到同事使用group_concat()函数 和concat_ws()函数,这两个函数和普通的concat()函数之间到底有什么不同. 我使用的数据库是mysql数据库. GROU ...

  5. lis框架showoncodename的用法

    fm.Sex.value=tContent2[0][3];//这个一定得是查询出来的码值alert("获取到的值是:"+tContent2[0][3]);showOneCodeNa ...

  6. IGC(Interleaved Group Convolutions)

    深度学习被引起关注是在2012年,用神经网络训练的一个分类模型在ImagNet上取得了第一名,而且其分类精度比第二名高出10多个点,当时所使用的模型为AlexNet,现在看来其为一个比较简单的网络,而 ...

  7. junit4的初级用法

    junit4初级用法: 一:各个标签的意思 1.@Test用来标注测试函数 2.@Before用来标注此函数在每次测试函数运行之前运行(每执行一个@Test之前都要运行一遍@Before) 3.@Af ...

  8. BZOJ1113 海报PLA1(单调栈入门题)

    一,自己思考下 1,先自己思考下 N个矩形,排成一排,现在希望用尽量少的海报去cover住它们. 2,不懂. 着实不懂. 3,分析下,最优性问题对吧,然后就每什么想法了.. 虽然肯定和单调栈和单调队列 ...

  9. Tensorflow细节-Tensorboard可视化-简介

    先搞点基础的 注意注意注意,这里虽然很基础,但是代码应注意: 1.从writer开始后边就错开了 2.writer后可以直接接writer.close,也就是说可以: writer = tf.summ ...

  10. video.js学习笔记

    video.js学习笔记获取用户观看时长