128. 最长连续序列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hy971216/article/details/82918542

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

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

示例:

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

分析:如果先进行排序在遍历求最长连续序列的长度,那么时间复杂度需要O(nlogn),但是这题要求时间复杂度为O(n).考虑用哈希表的想法,用一个哈希表unordered_map<int,bool> used来记录每个元素是否使用,以该元素在中心,向左右遍历,直到不连续为止,每次记录下向左向右扩张的最长长度。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int, bool> used;
        for(int i = 0; i < nums.size(); i++) {
            used[nums[i]] = false;
        }
        int longest = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(used[nums[i]]) {
                continue;
            }
            int length = 1;
            used[nums[i]] = true;
            for(int j = nums[i] + 1; used.find(j) != used.end(); ++j) {
                used[j] = true;
                ++length;
            }
            for(int j = nums[i] - 1; used.find(j) != used.end(); --j) {
                used[j] = true;
                ++length;
            }
            longest = max(longest, length);
        }
        return longest;
    }
};

猜你喜欢

转载自blog.csdn.net/hy971216/article/details/82918542