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.
    最好想到的思路是排序,如果排序,最快也要O(NlogN),不符合要求。
    以空间换时间:
    代码:

    int longestConsecutive(vector<int>& nums)
    {
        map<int,int> map1;
        int len = 0;
        int maxlen = len;
        for(int i = 0;i<nums.size();i++)
        {
           //在nums中出现,则不为0,否则为0
           map1[nums[i]]++;
        }
        int min1 = nums[0];
        int min_up = min1;
        int min_down = min1-1;
        int i = 0;
        while(i<nums.size())
        {
              if(map1[min_up]!=0)
              {
                    len++;
                    map1[min_up] = 0;
                    min_up++;
              }
              if(map1[min_down]!=0)
              {
                     len++;
                     map1[min_down] = 0;
                     min_down--;
              }
              if(map1[min_down]==0 && map1[min_up]==0)
              {
                     if(maxlen<len)
                     maxlen = len;  
                     cout<<maxlen<<endl;
                     len = 0; 
                     while(map1[nums[i++]]==0&&i<nums.size());
                     if(i<nums.size())
                     {
                          min1 = nums[i-1];
                          min_up = min1;
                          min_down = min1-1;    
                     }
                     else break;                           
              }
        }
        return maxlen;
    }

    时间复杂度:O(N),同时引入了map,空间复杂度O(N).

  • 相关阅读:
    select/poll/epoll 对比
    I/O Mutiplexing poll 和 epoll
    Socket 编程IO Multiplexing
    ubuntu12.04 lts 安装gcc 4.8
    time since epoch
    ceph-RGW Jewel版新概念
    支持向量机(svm)
    MachineLearning之Logistic回归
    ML之回归
    ML之监督学习算法之分类算法一 ——— 决策树算法
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601424.html
Copyright © 2011-2022 走看看