[LeetCode] 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.

 

这道题要求求最长连续序列,并给定了O(n)复杂度限制,所以很自然想到了哈希表,其查找速度为常数级,我们的解题思路是先把原数组中的所有数存入哈希表中,然后对于每一个数字,在其递增递减方向依次搜索,并记录连续长度,每遍历完一个数字,便将其移出哈希表,最终遍历完所有数字,可得答案。代码如下:

 

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        int res = 0;
        unordered_map<int, int> numMap;
        for (int i = 0; i < num.size(); ++i) {
            numMap[num[i]] = i;
        }
        for (int i = 0; i < num.size(); ++i) {
            int d = num[i];
            int n = 1;
            numMap.erase(d);
            while (numMap.find(++d) != numMap.end()) {
                ++n;
                numMap.erase(d);
            }
            d = num[i];
            while (numMap.find(--d) != numMap.end()) {
                ++n;
                numMap.erase(d);
            }
            res = max(res, n);
        }
        return res;
    }
};

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)