128. 最长连续序列 找目标序列的最小数或者最大数

题目

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

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

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

思路

最长连续序列一定是从序列的最小数开始,到序列的最大数结束,或者最大数到最小数。

  • 无需重复计算,只需指定一种方向,这里找最小数到最大数的序列长度。
  • 若一个数小1的数在集合里出现,则这个数不是最小数,则其增长序列一定不是最长的。

解法:将所有数放到hash集合里,降低查找复杂度

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> set;                  //集合初始化
        for (int i : nums)
            set.insert(i);

        int max = 0;                             //数组有可能为空
        for (auto ite = set.begin(); ite != set.end(); ++ite) {
            if (!set.count(*ite - 1)) {          //找目标序列最小数
                int max_tmp = 1;
                int i = 1;
                while (set.count(*ite + i)) {
                    ++i;
                    ++max_tmp;
                }
                if (max_tmp > max)
                    max = max_tmp;
            }
        }

        return max;
    }
};

 优化上述编码,得到如下程序:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> set(nums.begin(), nums.end()); //初始化set

        int max = 0;
        for (int num : set) {                             //按值遍历
            if (!set.count(num - 1)) {
                int max_tmp = 1;
                while (set.count(++num))                  //去掉迭代器减少临时变量
                    ++max_tmp;

                if (max_tmp > max)
                    max = max_tmp;
            }
        }

        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/sy_123a/article/details/109035485