128. Longest Consecutive Sequence

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了128. 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.

===================

给一个未排序数组,找到一个最长的连续数组,返回其长度.

====

思路:

利用一个hash表,存储已经扫描的数组元素,

对数组中每一个curr元素,都必须在hash表中向前查找,向后查找.

===

code:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int,bool> hash_used;
        for(auto i:nums){
            hash_used[i] = false;
        }
        int longest = 0;
        for(auto i:nums){
            if(hash_used[i])
                continue;
            int length = 1;

            hash_used[i] = true;

            for(int j = i+1;hash_used.find(j)!=hash_used.end();j++){
                hash_used[j] = true;
                length++;
            }
            for(int j = i-1;hash_used.find(j)!=hash_used.end();j--){
                hash_used[j] = true;
                length++;
            }
            longest = max(longest,length);
        }//for
        return longest;
    }
};

 

以上是关于128. Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence