Longest Consecutive Sequence

来源:互联网 发布:专业流量控制软件 编辑:程序博客网 时间:2024/06/06 06:55

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]. Return its length: 4.

Your algorithm should run in O(n) complexity.

解析:

若是连续的序列那么用该序列中任意一个数字都能找到该序列,那么遍历每个元素,找每个元素的序列,并把经过的元素都置为已访问,下次不再遍历这些元素。

代码:

class Solution {public:    int longestConsecutive(vector<int>& nums) {                unordered_map<int,int>m;        for (int i=0; i<nums.size(); i++)        {            m[nums[i]]=1;        }        int ans=0;        int tempans=0;        for (int i=0; i<nums.size(); i++)        {            tempans=1;            if (m.count(nums[i])&&m[nums[i]])            {                m[nums[i]]=0;                int left=nums[i]-1;                while (m.count(left)&&m[left])                {                    m[left--]=0;                    tempans++;                                    }                int right=nums[i]+1;                while(m.count(right)&&m[right])                {                    m[right++]=0;                    tempans++;                }            }                        if (ans<tempans)            {                ans=tempans;            }        }        return ans;            }};



0 0
原创粉丝点击