128. Longest Consecutive Sequence

来源:互联网 发布:怎样优化win7开机时间 编辑:程序博客网 时间:2024/06/04 01:41

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) {        unordered_set<int> record(nums.begin(),nums.end());        int res=0;        for(int n:nums){            if(record.find(n)==record.end()) continue;            record.erase(n);            int prev=n-1,post=n+1;            while(record.find(prev)!=record.end()) record.erase(prev--);            while(record.find(post)!=record.end()) record.erase(post++);            res=max(res,post-prev-1);        }        return res;    }};