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

leetcode Longest Consecutive Sequence

2015-12-09 20:15 483 查看
原题链接:https://leetcode.com/problems/longest-consecutive-sequence/

Description

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 {
private:
typedef vector<int> vec;
typedef unordered_map<int, bool> UMAP;
public:
int longestConsecutive(vec &nums) {
if(nums.empty()) return 0;
UMAP vis;
int ans = 0;
for(auto &r: nums) vis[r] = false;
for(auto &r: nums) {
if(vis[r]) continue;
int ret = 1;
vis[r] = true;
for(int j = r + 1; vis.find(j) != vis.end(); j++) {
vis[j] = true;
ret++;
}
for(int j = r - 1; vis.find(j) != vis.end(); j--) {
vis[j] = true;
ret++;
}
ans = max(ans, ret);
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: