From : https://leetcode.com/problems/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.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
map<int, bool> has;
int len = nums.size();
for(int i=0; i<len; ++i) {
has[nums[i]] = true;
}
int num = 0;
for(int i=0; i<len; ++i) {
int cur = 1;
if(has[nums[i]]) {
// left
for(int k=nums[i]-1;; --k) {
if(has[k]) {
++cur;
has[k] = false;
} else{
break;
}
}
// right
for(int k=nums[i]+1;; ++k) {
if(has[k]) {
++cur;
has[k] = false;
} else{
break;
}
}
}
if(cur > num) {
num = cur;
}
}
return num;
}
};
本文介绍了一种算法,用于从无序整数数组中找出最长连续元素序列的长度,并确保算法的时间复杂度为O(n)。示例:对于数组[100,4,200,1,3,2],最长连续序列是[1,2,3,4],返回其长度4。
909

被折叠的 条评论
为什么被折叠?



