Leetcode: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.

 

class Solution {

public:

    int longestConsecutive(vector<int> &num) {

        std::unordered_map<int, bool> hash;

        for (int i = 0; i < num.size(); ++i) {

            hash.insert({num.at(i), false});

        }

        int maxLen = 0;

        int curLen = 0;

        for (int i = 0; i < num.size(); ++i) {

            auto iter = hash.find(num.at(i));

            if (iter->second == true) {

                continue;

            }

            iter->second = true;

            curLen = 1;

            for (int value = num.at(i) - 1; hash.find(value) != hash.end(); --value) {

                ++curLen;

                hash.find(value)->second = true;

            }

            for (int value = num.at(i) + 1; hash.find(value) != hash.end(); ++value) {

                ++curLen;

                hash.find(value)->second = true;

            }

            maxLen = std::max(maxLen, curLen);

        }

        return maxLen;

    }

};

 

题目要求是O(n)复杂度,而且元素都是无序的,我们首先想到使用哈希

用一个哈希表 unordered_map<int, bool> used 来记录每个元素是否使用,对每个元素,往左右两边扩张,直到不连续位置。

注意在两边扩张的时候,对已经计算的元素 必须记录为true,防止重复记录

例如 1 2 3 4  现在我们以1为中心向右边扩张,这是2,3,4都记录为true,所以以1为中心计算完之后,

遍历到2,3,4时因为已经记录为true了,所以直接跳过,防止重复计算。

你可能感兴趣的:(LeetCode)