您的位置:首页 > 产品设计 > UI/UE

Leetcode: Longest Consecutive Sequence

2014-01-03 19:14 218 查看
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.

以前看过,用Hash。

class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int, int> conseq;
for (int i = 0; i < num.size(); ++i) {
if (conseq.find(num[i]) == conseq.end()) {
auto lessi = conseq.find(num[i] - 1);
auto greati = conseq.find(num[i] + 1);
if (lessi != conseq.end() && greati != conseq.end()) {
int merged = lessi->second + greati->second + 1;
conseq[num[i] - lessi->second] = merged;
conseq[num[i] + greati->second] = merged;
conseq[num[i]] = 1;
}
else if (lessi != conseq.end()) {
conseq[num[i]] = lessi->second + 1;
conseq[num[i] - lessi->second] = lessi->second + 1;
}
else if (greati != conseq.end()) {
conseq[num[i]] = greati->second + 1;
conseq[num[i] + greati->second] = greati->second + 1;
}
else {
conseq[num[i]] = 1;
}
}
}

int max_length = 0;
for_each(conseq.begin(), conseq.end(), [&max_length] (unordered_map<int, int>::value_type &x) {
max_length = max(x.second, max_length);
});

return max_length;
}
};

貌似也可以用Segment Tree,不过应该不是O(n)了。

=======================第二次=======================

class Solution {
public:
int longestConsecutive(vector<int> &num) {
int max_length = 0;
unordered_map<int, int> seq_map;
for (int i = 0; i < num.size(); ++i) {
if (seq_map.find(num[i]) != seq_map.end()) {
continue;
}

int length = 1;
auto preIter = seq_map.find(num[i] - 1);
if (preIter != seq_map.end()) {
length += preIter->second;
}
auto postIter = seq_map.find(num[i] + 1);
if (postIter != seq_map.end()) {
length += postIter->second;
}
seq_map[num[i]] = length;
if (preIter != seq_map.end()) {
seq_map[num[i] - preIter->second] = length;
}
if (postIter != seq_map.end()) {
seq_map[num[i] + postIter->second] = length;
}

max_length = max(max_length, length);
}

return max_length;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode