【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;
    }
};

看这简洁的代码。。。。

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