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

    unordered_set是C++自带的hash表

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(num.size()==0)return 0;
            unordered_set<int> m;
            for(int i=0;i<num.size();i++){
                m.insert(num[i]);
            }
            int max=0;
            while(m.size()!=0){
                int v=*m.begin();
                m.erase(v);
                int i1=0,i2=0,v1=v-1,v2=v+1;
                while(m.find(v1)!=m.end()){
                    m.erase(v1);
                    v1--;
                    i1++;
                }
                while(m.find(v2)!=m.end()){
                    m.erase(v2);
                    v2++;
                    i2++;
                }
                int length=i1+i2+1;
                if(length>max){
                    max=length;
                }
            }
            return max;
        }
    };
    
  • 相关阅读:
    nuxt实践
    安卓H5软键盘遮挡输入框
    h5复制粘贴板,打开APP功能
    MVC3
    MVC3
    C#高编
    接口的显式实现(转)
    E-Retail 框架学习
    C#高编
    实现DIV居中布局三种途径(转)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3330131.html
Copyright © 2011-2022 走看看