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(n),所以不行!这题可以使用到关联容器的知识(见博客关联容器详解(一))。然后就涉及选择容器的问题了,是选择有序的set,还是无序的unordered_set(当然可以使用map类的)?因为set会直接给元素进行排序,其原理涉及平衡搜索二叉树(即红黑树),时间复杂度不满足。所以这里利用unordered_set。大致的思路是:从头到尾遍历数组,若某数在set中,则遍历其左右两边的数(注意,这里是数组存放的值不是下标),并删除该数。找到目前的最大长度,在继续访问数组中的元素。代码如下:

     1 class Solution {
     2 public:
     3     int longestConsecutive(vector<int> &num) 
     4     {
     5         int res=0;
     6         unordered_set<int> s(num.begin(),num.end());
     7 
     8         for(int i=0;i<num.size();++i)
     9         {
    10             if(s.count(num[i]))
    11             {
    12                 s.erase(num[i]);
    13                 int pre=num[i]-1,next=num[i]+1;
    14                 while(s.count(pre))
    15                     s.erase(pre--);
    16                 while(s.count(next))
    17                     s.erase(next++);
    18                 
    19                 res=max(res,next-pre-1);
    20             }
    21         }  
    22         return res;
    23     }
    24 };

    关于unordered_map的使用方法可以参见Grandyang的博客。

  • 相关阅读:
    个人项目作业
    软件工程个人博客作业
    软件工程热身作业
    OO第四单元作业总结
    OO第三单元作业总结
    OO第二单元作业总结
    酸甜苦辣皆阅历,悲欢离合尽人生——软件工程个人总结
    Centos7里yum出问题可以试试
    idea 报错 Two modules in a project cannot share the same content root
    关于本地git的补充
  • 原文地址:https://www.cnblogs.com/love-yh/p/7090526.html
Copyright © 2011-2022 走看看