zoukankan      html  css  js  c++  java
  • 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.

    不是自己想出来的,但是有所改进。

    题目要求O(n)。如果所有常规办法都不奏效,O(n)就只能靠hash了,必须底层不能是红黑树的哈希。

    但即便用哈希,也要小心元素的重复,所以查到一个,删除一个。

    关键是底层要用unordered_map

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            unordered_set<int> l;
            if(num.size()<=1)return num.size();
            for(int i = 0 ; i < num.size(); i++)
            {
                l.insert(num[i]);
            }
            
            
            int max = 1;
            for(int i = 0 ; i < num.size();i++)
            {
                if(l.find(num[i]) == l.end())continue;
                
                int temp = num[i];
                int len =1 ;
                temp--;
                while(l.find(temp)!=l.end())
                {
                    l.erase(temp);
                    temp--;
                    len++;
                }
                temp = num[i]+1;
                
                while(l.find(temp)!=l.end())
                {
                    l.erase(temp);
                    temp++;
                    len++;
                }
                l.erase(num[i]);
                if(len > max)max =len;
                
            }
            return max;
        }
    };
    

      

  • 相关阅读:
    硬件调试软件
    ICMP(Internet Control Message Protocol)
    算法网站
    下载安装
    netcat 实现端口转发
    mqtt 连接工具
    Linux(CentOS7)安装zip、unzip命令
    awk 两个字符串互换位置
    创建一个swift项目
    屏幕录制
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3666481.html
Copyright © 2011-2022 走看看