lintcode-124-最长连续序列

124-最长连续序列

给定一个未排序的整数数组,找出最长连续序列的长度。

说明

要求你的算法复杂度为O(n)

样例

给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4

标签

数组

思路

由于限定了时间复杂度为 O(n),所以采取先排序再遍历的方式是不适合的,于是以空间换时间,用 set 存储 num 中的数字,方便检测 num 中某个数字是否存在,思路如下:

  1. 遍历 num 数组中的每个数字,如果其在 set 中存在,那么将其移除,然后分别用两个变量 pre 和 next 算出其前一个数跟后一个数,然后在集合中循环查找,
  2. 如果 pre 在 set 中,那么将 pre 移除集合,然后 pre--,直至pre不在集合之中,对next采用同样的方法,
  3. next-pre-1就是当前数字的最长连续序列

code

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    int longestConsecutive(vector<int> &num) {
        // write you code here
        int size = num.size(),result = 0;
        if(size <= 0) {
            return 0;
        }
        
        set<int> s(num.begin(), num.end());

        for (int i=0; i<size; i++) {
            if(!s.count(num[i])) {
                continue;
            }
            s.erase(num[i]);
            int pre = num[i] - 1, next = num[i] + 1;
            while(s.count(pre)) {
                s.erase(pre--);
            }
            while(s.count(next)) {
                s.erase(next++);
            }
            result = result > next-pre-1 ? result : next-pre-1;
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7210791.html