[leetcode]128. Longest Consecutive Sequence

来源:互联网 发布:hadoop能用python吗 编辑:程序博客网 时间:2024/05/23 11:50

题目链接: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{public:    int longestConsecutive(vector<int>& nums)    {        if(nums.empty()) return 0;        unordered_set<int> record(nums.begin(),nums.end());        int res=1;        for(int n :nums)        {            if(record.find(n)==record.end()) continue;            record.erase(n);            int prev=n-1,next=n+1;            while(record.find(prev)!=record.end()) record.erase(prev--);            while(record.find(next)!=record.end()) record.erase(next++);            res=max(res,next-prev-1);        }        return res;    }};


原创粉丝点击