23longest-consecutive-sequence

题目描述

给定一个无序的整数类型数组,求最长的连续元素序列的长度。
例如:
给出的数组为[100, 4, 200, 1, 3, 2],
最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
你需要给出时间复杂度在O(n)之内的算法

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.

示例1

输入

复制
[100, 4, 200, 1, 3, 2]

输出

复制
4

class Solution {
public:
    /**
     *
     * @param num int整型vector
     * @return int整型
     */
    int longestConsecutive(vector<int>& num) {
        // write code here
        set<int> Set(num.begin(),num.end());
        int result=1;
        for (int x:num)
        {
            if (Set.find(x)==Set.end())
                continue;
            Set.erase(x);
            int l=x-1,r=x+1;
            while (Set.find(l)!=Set.end())
                Set.erase(l--);
            while (Set.find(r)!=Set.end())
                Set.erase(r++);
            result=max(result,r-l-1);
            
        }
        return result;
    }
    
};

原文地址:https://www.cnblogs.com/hrnn/p/13413245.html