问题

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

通过并查集对这道题进行求解

class Solution{
public:
      undered_map<int,int> F;
      int father(int x)
      {
            if(F.count(x)==0)return x;
            if(F[x]!=x)F[x]=father(x);
            return F[x];
      } 
      int longestConsecutive(vector<int> &nums)
      {
            F.clear();
            for(auto x:nums)
            {
                  F[x]=father(x);
                  if(F.count(x-1)>0) F[father(x-1)]=father(x);
                  if(F.count(x+1)>0) F[father(x+1)]=father(x+1);
            }
            int res = 0;
            for (auto x:nums)
            {
                  if(father(x)-x+1>res)
                        res = father(x) - x + 1;
            }
            return res;
      }      

}

或者用set来去重,然后遍历每一个元素,检测x-1是否存在如果存在则不进行计数,如果不存在则查找x+1,一直查找到不存在。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> num_set;
        for(const int &num:nums)
        {
            num_set.insert(num);
        }
        int longStreak = 0;
        for(const int &num:num_set)
        {
            if(!num_set.count(num-1))
            {
                int currentNum = num;
                int currentSteak = 1;
                cout<<currentNum;
                while(num_set.count(currentNum+1))
                {
            
                    currentNum++;
                    currentSteak++;
                }
                //cout<<endl;
                
            longStreak = max(longStreak,currentSteak);
            }
        }
        return longStreak;
    }
};
posted on 2020-06-06 07:56  吕店老板  阅读(87)  评论(0编辑  收藏  举报