128. Longest Consecutive Sequence

来源:互联网 发布:网络流行aq是什么意思 编辑:程序博客网 时间:2024/06/06 09:28

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(n)。用unordered_set来实现,先用序列的全部元素构造哈系表,然后对于序列中的每一个数,往两边查找与之连续的数,计算出个数,最后求全部个数的最大值。为了避免重复查找,访问过的数都在哈系表中删除。


代码:

class Solution{public:int longestConsecutive(vector<int>& nums){int res = 0;unordered_set<int> umap(nums.begin(), nums.end());for(auto num:nums){if(umap.find(num) == umap.end()) continue;int tmp = num - 1, cnt = 1;while(umap.find(tmp) != umap.end()) {umap.erase(tmp--);++cnt;}tmp = num + 1;while(umap.find(tmp) != umap.end()) {umap.erase(tmp++);++cnt;}res = max(res, cnt);}return res;}};


0 0
原创粉丝点击