Longest Consecutive Sequence
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)复杂度的算法来求出一个序列中能够构成的最长递增子序列。
由于有递增和O(n)。首先想到的就是基数排序的方法来解决该问题。因此我构造了第一次使用了一个数组来实现基数排序。但是很不幸的是,测试数据中有一个数超过了int。因此我又使用了HashMap来实现。
代码
class LongestConsecutiveSequence {
public int longestConsecutive(int[] num) {
int res = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int n : num) {
//如果包含n这个数
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;
// 计算它左右两边最大连续序列的长度之和并加上自身长度
int sum = left + right + 1;
map.put(n, sum);
// 记录最大的连续序列长度
res = Math.max(res, sum);
// 将最大长度记录到序列头部和尾部
map.put(n - left, sum);
map.put(n + right, sum);
}
else {
continue;
}
}
return res;
}
}