注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
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.
你看到[100, 4, 200, 1, 3, 2]这个数组,首先你会看99或者101在不在这个数组里,发现数组没这两个数,那么100组成的连续序列长度仅为1。接着会看5或者3在不在数组里,会发现3存在,5不存在;紧接着会看2在不在…直到发现0不在。从而得到4组成的最长序列为4。哈希表查询时间复杂度为O(1)。每个元素只被查找一次,总时间复杂度为O(n)。
class Solution {
public:
int longestConsecutive(const vector<int>& nums) {
unordered_map<int, bool> used;
for (auto i : nums) used[i] = false;
int longest = 0;
for (auto i : nums) {
if (used[i]) continue;
int length = 1;
used[i] = true;
for (int j = i + 1; used.find(j) != used.end(); ++j) {
used[j] = true;
++length;
}
for (int j = i - 1; used.find(j) != used.end(); --j) {
used[j] = true;
++length;
}
longest = max(longest, length);
}
return longest;
}
};