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

Longest Consecutive Sequence 最长连续子序列

2014-08-10 23:21 134 查看
题目:

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:
map<int, int> mp;
int longestConsecutive(vector<int> &num) {
int i, j;
for(i = 0; i < num.size(); i++)
mp[num[i]] = 1;
int max = 0;
for(i = 0; i < num.size(); i++)
{
int sum = 1;
if(mp.count(num[i])){
mp[num[i]] = 0;
int left = num[i] -1;
while(mp.count(left) && mp[left] != 0)
{
mp[left--] = 0;
sum++;
}
int right = num[i] + 1;
while(mp.count(right) && mp[right] != 0){
mp[right++] = 0;
sum++;
}

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