LeetCode—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.

最好想到的思路是排序,如果排序,最快也要O(NlogN),不符合要求。

以空间换时间:

代码:

int longestConsecutive(vector<int>& nums)
{
map<int,int> map1;
int len = 0;
int maxlen = len;
for(int i = 0;i<nums.size();i++)
{
//在nums中出现,则不为0,否则为0
map1[nums[i]]++;
}
int min1 = nums[0];
int min_up = min1;
int min_down = min1-1;
int i = 0;
while(i<nums.size())
{
if(map1[min_up]!=0)
{
len++;
map1[min_up] = 0;
min_up++;
}
if(map1[min_down]!=0)
{
len++;
map1[min_down] = 0;
min_down--;
}
if(map1[min_down]==0 && map1[min_up]==0)
{
if(maxlen<len)
maxlen = len;
cout<<maxlen<<endl;
len = 0;
while(map1[nums[i++]]==0&&i<nums.size());
if(i<nums.size())
{
min1 = nums[i-1];
min_up = min1;
min_down = min1-1;
}
else break;
}
}
return maxlen;
}

时间复杂度:O(N),同时引入了map,空间复杂度O(N).

上一篇:转载:fstream和ifstream详细用法


下一篇:Windows10下打开MySQL服务 & 查看MySQL服务是否启动