• 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;
        }
    };
  • 相关阅读:
    conda安装使用
    数据库删除后台代码
    表格显示数据库(html和php混编)
    唯一用户名jquery和PHP代码
    //阿贾克斯提交数据库
    //向数据库添加数据(form表单提交)
    //conn数据库配置
    Css 变量
    input标签让光标不出现
    Es6Class
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5621895.html
Copyright © 2020-2023  润新知