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