LeetCode128.最長連續序列 每日一題6月6日

問題描述:

給定一個未排序的整數數組,找出最長連續序列的長度。

要求算法的時間複雜度爲 O(n)。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-consecutive-sequence

示例:

輸入: [100, 4, 200, 1, 3, 2]
輸出: 4
解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度爲 4。

解題思路:

題意是時間複雜度爲O(n),那麼我們肯定不能使用傳統排序方法

那麼只有使用空間換時間的方法,使用hash表一一映射

然後在查找是否有連續的

這裏採用unordered_set數據結構,unordered_set的查找是基於哈希表的,並且具有去重複的功能

下面是完整代碼:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> se(nums.begin(),nums.end());
        int res =0;
        for(auto &x:se){
            if(!se.count(x-1)){
                int cnt =1,num=x;
                while(se.count(num+1)){cnt++;num++;}
                res = max(res,cnt);
            }
        }
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章