Longest Consecutive Sequence

简介: 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].

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.

C++代码实现:

#include<iostream>
#include<vector>
#include<set>
using namespace std;

class Solution
{
public:
    int longestConsecutive(vector<int> &num)
    {
        if(num.empty())
            return 0;
        set<int> st;
        int len=1;
        for(int i=0; i<(int)num.size(); i++)
            st.insert(num[i]);
        auto k=st.begin();
        k++;
        int count=1;
        for(; k!=st.end(); k++)
        {
            auto tmp=k;
            tmp--;
            if(*tmp+1!=*k)
            {
                if(count>len)
                    len=count;
                count=1;
                continue;
            }
            count++;
        }
        if(count>len)
            len=count;
        return len;
    }
};

int main()
{
    Solution s;
    vector<int> vec= {9,1,4,7,3,-1,0,5,8,-1,6};
    cout<<s.longestConsecutive(vec)<<endl;
}

 

相关文章
|
算法
LeetCode 128. Longest Consecutive Sequence
给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
63 0
LeetCode 128. Longest Consecutive Sequence
|
算法
LeetCode 300. Longest Increasing Subsequence
给定一个无序的整数数组,找到其中最长上升子序列的长度。
34 0
LeetCode 300. Longest Increasing Subsequence
|
存储
LeetCode 329. Longest Increasing Path in a Matrix
给定一个整数矩阵,找出最长递增路径的长度。 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
45 0
LeetCode 329. Longest Increasing Path in a Matrix
|
算法 C#
算法题丨Longest Consecutive Sequence
描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
1089 0
1085. Perfect Sequence (25)
#include #include #include using namespace std; int main() { int n; long p; cin >> n >> p; v...
837 0
Time range (447392) for take &#39;Take 001&#39; is larger than maximum allowed(100000).
http://www.cnblogs.com/lopezycj/archive/2012/05/16/unity3d_tuchao.html   https://forum.unity3d.com/threads/time-range-447406-for-translation-curve-s-on-node-bone001-on-take-take-001-what-the.