Longest Consecutive Sequence 题解

题目来源: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.

解题思路:

利用hashmap

用一个set/map记录每个数,然后挨个找相邻的数字,每找到一个就从原set/map中去掉,直到全部遍历完毕。

    int longestConsecutive(vector<int> &num)
    {
        int result = 0;
        unordered_set<int> data(num.begin(), num.end());
        while(! data.empty())
        {
            int v = *(data.begin());
            data.erase(data.begin());
            int i = 1;
            int len = 1;
            while(data.find(v-i) != data.end())
            {
                ++len;
                data.erase(data.find(v-i));
                ++i;
            }
            i = 1;
            while(data.find(v+i) != data.end())
            {
                ++len;
                data.erase(data.find(v+i));
                ++i;
            }
            result = std::max(result, len);
        }
        return result;
    }

先利用O(n)的排序

这也是参考了discuss的答案。 先用一个O(n)的排序算法,然后挨个左右看就是。 注意数组中可能含有相同的数字以及负数。

这里用基数排序radixsort,注意基数排序中内部计数排序时注意,输入可能含有负数,因此映射的下标不能是[0,9],而是还得把负数的另外一半算上即[0,18],-9->0, 9->18.

Last updated

Was this helpful?