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).

  • 相关阅读:
    MSP430G2553 4x4矩阵键盘
    数论 (1)
    吐血分享一款免费看所有付费影视的app,不好用来石欠我
    Nginx如何部署静态web项目
    SpringBoot-RestTemplate实现调用第三方API
    信息收集小技巧
    kali常用命令
    kali中的Firefox改中文
    反射与注解
    MyBatis-Plus 基本用法
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601424.html
Copyright © 2011-2022 走看看