【LeetCode 128】 Longest Consecutive Sequence

題目描述

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

思路

思路一:

每次遍歷到一個數字num,根據num-1、num+1兩個數字的連續數字長度來更新當前數字的連續長度。每次要更新首尾。

思路二:
所有數字放在一個set裏,遍歷所有數字,如果當前數字是一個左端點,尋找長度。

代碼

代碼一:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if (nums.empty()) return 0;
        unordered_map<int, int> mp;
        int n = nums.size();
        int res = 1;
        
        for (auto num : nums) {
            if (mp[num]) continue;
            mp[num] = 1;
            int st = num, ed = num;
            if (mp[num-1] + 1 > mp[num]) {
                int cnt = mp[num-1] + 1;
                mp[num] = cnt;
                st = num - cnt + 1;
                ed = num;
            }
            if (mp[num+1] + 1 > mp[num]) {
                int cnt = mp[num+1] + 1;
                mp[num] = cnt;
                st = num;
                ed = num + cnt - 1;
            }
            if (mp[num-1] + mp[num+1] + 1 > mp[num]) {
                int cnt = mp[num-1] + mp[num+1] + 1;
                mp[num] = cnt;
                st = num - mp[num-1];
                ed = num + mp[num+1];
            }
            res = max(res, mp[num]);
            mp[st] = mp[num];
            mp[ed] = mp[num];
        }
        
        return res;
    }
};

代碼二:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if (nums.empty()) return 0;
        unordered_set<long long> st(nums.begin(), nums.end());
        int res = INT_MIN;
        
        for (auto num : st) {
            if (st.count(num-1)) continue;
            int l = 0;
            while(st.count(num++)) l++;
            res = max(res, l);
        }
        
        return res;
    }
};

看這簡潔的代碼。。。。

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