算法练习-最长连续序列

91 阅读1分钟

题目是要求在数组中寻找最长的连续数字序列,但是序列并不会在数组中有序,且要求时间复杂度为O(n)O(n)

思路

题目标签是哈希,但是如何计算一个哈希值来判断该序列是否连续,连续长度多少,并不容易。

但是,正确思路是,在map中搜索序列起始值,再搜索该值的+1、+2 ... +(size - i + 1)的值是否在map中。

踩坑

边界值处理

1.当数字长度为1或者0: 最长长度为数组长度;

2.当数组内均为同一元素: 序列长度的初始化值应为1;

3.当数组特别大,具有特别多的重复值,此时容易超时: 遍历map内的值即可。

实现

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if (nums.size() < 2) { return nums.size(); }

        std::set<int> rbSet;
        int vecSize = nums.size();
        for (int i = 0; i <vecSize; i++ ) {
            rbSet.insert(nums[i]);
        }

        if (rbSet.size() == 1) { return 1; }

        int maxSequLen = 1;

        int seqLen = 0;
        int j = 1;
        int index = 0;
        int count = 0;
        int indexLimit = 0;
        for (int val: rbSet) {
            if ( rbSet.find(val -1) != rbSet.end()) { continue; }
            indexLimit = (rbSet.size() - count + 1);
            index = 1;
            seqLen = 1;
            while (index < indexLimit && rbSet.find(val + index) != rbSet.end()) {
                seqLen += 1;
                index += 1;
                if (seqLen > maxSequLen) {
                    maxSequLen = seqLen;
                }
            }
            count ++;
        }
        return maxSequLen;
    }
};