• 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表中向前查找,向后查找,找出此nums[curr]过在连续数组。

    maxlength = max(maxlength,length);

    ===

    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;
        }
    };
  • 相关阅读:
    [CQOI2011]放棋子
    [CF1192B]动态直径
    [CERC2016]凸轮廓线
    19_08_14-19_08_21校内训练 补题
    [模板]线性递推+BM
    19_08_10[校内训练]割图
    [模板]多项式封装(无讲解)
    19_07_11校内训练[字串染色]
    CF990G
    19_07_09校内训练[分组]
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5621895.html
Copyright © 2020-2023  润新知