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.
拿到這道題目,第一反應就是沒有思路TT。想了好久也只想到把全部元素排序,然後再去遍歷一遍。但這樣做的複雜度是O(nlgn),因爲這是常用排序的最低複雜度。看了網上的幾個解答感覺用散列表(哈希表)是一個很不錯的想法,自己竟然忘記STL這麼好用的東西,真是該死。
把數組元素全部放到一個map裏去,數組元素作爲key,value設爲1,然後再檢查每一個數組元素的左右相鄰的數字是否在map中,以此得到最大的連續序列的長度。
代碼實現如下:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
map<int, int> m;
int result= 0;
for (int i = 0; i < num.size();i++){
m[num[i]] = 1;
}
for (int i = 0; i < num.size(); i++){
int tmp = 1;
if (m.count(num[i])){
m[num[i]] = 0;
int left = num[i] - 1;
while (m.count(left) && m[left] != 0){
m[left--] = 0;
tmp++;
}
int right = num[i] + 1;
while (m.count(right) && m[right] != 0){
m[right++] = 0;
tmp++;
}
}
result = result >= tmp ? result : tmp;
}
return result;
}
};