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.

Subscribe to see which companies asked this question

如果允许$O(n \log n)$的复杂度,那么可以先排序,可是本题要求$O(n)$。

由于序列里的元素是无序的,又要求$O(n)$,首先要想到用哈希表。

用一个哈希表 {unordered_map<int, bool> used}记录每个元素是否使用,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。

 // Leet Code, Longest Consecutive Sequence
 // 时间复杂度O(n),空间复杂度O(n)
 class Solution {
 public:
     int longestConsecutive(const vector<int> &num) {
         unordered_map<int, bool> used;

         for (auto i : num) used[i] = false;

         ;

         for (auto i : num) {
             if (used[i]) continue;

             ;

             used[i] = true;

             ; used.find(j) != used.end(); ++j) {
                 used[j] = true;
                 ++length;
             }

             ; used.find(j) != used.end(); --j) {
                 used[j] = true;
                 ++length;
             }

             longest = max(longest, length);
         }

         return longest;
     }
 };
67 / 67 test cases passed.
Status:

Accepted

Runtime: 26 ms
 // Leet Code, Longest Consecutive Sequence
 // 时间复杂度O(n),空间复杂度O(n)
 // Author: @advancedxy
 class Solution {
 public:
     int longestConsecutive(vector<int> &num) {
         unordered_map<int, int> map;
         int size = num.size();
         ;
         ; i < size; i++) {
             if (map.find(num[i]) != map.end()) continue;
             map[num[i]] = ;
             ) != map.end()) {
                 l = max(l, mergeCluster(map, num[i] - , num[i]));
             }
             ) != map.end()) {
                 l = max(l, mergeCluster(map, num[i], num[i] + ));
             }
         }
          ?  : l;
     }

 private:
     int mergeCluster(unordered_map<int, int> &map, int left, int right) {
         ;
         ;
         ;
         map[upper] = length;
         map[lower] = length;
         return length;
     }
 };
 class Solution {
 public:
     int longestConsecutive(vector<int> &num) {
         // Start typing your C/C++ solution below
         // DO NOT write int main() function

         priority_queue<int> Q;
         ; i < num.size(); i++) {
             Q.push(num[i]);
         }
         ;
         ;
         int temp = Q.top();
         Q.pop();
         while (!Q.empty()) {
              == Q.top()) {
                 temp -= ;
                 maxlen += ;
             } else if (temp != Q.top()) {
                 temp = Q.top();
                 maxlen = ;
             }
             Q.pop();
             ret = max(maxlen, ret);
         }
         return ret;
     }
 };

 // O(n) solution

 class Solution {
 public:
     int longestConsecutive(vector<int> &num) {
         unordered_map<int, int> longest;
         ;

         ; i < num.size(); i++) {
             ) {
                 continue;
             }

             ];
             ];
             ;

             longest[num[i]] = bound;
             longest[num[i]-leftbound] = bound;
             longest[num[i]+rightbound] = bound;

             if (result < bound) {
                 result = bound;
             }
         }
         return result;
     }
 };
 #include <stdlib.h>
 #include <stdio.h>
 #include <string>
 #include <iostream>
 #include <unordered_set>
 #include <vector>
 #include <set>
 #include <algorithm> // sort
 #include <functional>//greater<type>() model
 using namespace std;

 class Solution {
 public:
     vector<int>::iterator vii;
     set<int>::iterator sii;
     int longestConsecutive(vector<int>& nums) {
         ;
         ;
         sort(nums.begin(), nums.end(), less<int>());

         for (vii = nums.begin(); vii != nums.end();) {
             int tmp;
             tmp = *vii;
             int next = *++vii;
             if(tmp == next){
                 //++vii;
                 continue;
             }
             ) != next){
                 if(result < ret){
                     result = ret;
                 }
                 ret = ;
                 continue;
             }else {
                 ret++;
             }
         }
         /*
         set<int> si;
         //copy(nums.begin(), nums.end(), std::back_inserter(si));
         copy(nums.begin(), nums.end(), si.begin());
         //sort(nums.begin(), nums.end(), less<int>());

         for (sii = si.begin(); sii != si.end();) {
             int tmp;
             tmp = *sii;
             int next = *++sii;
             if((tmp+1) != next){
                 if(result < ret){
                 result = ret;
                 }
                 ret = 0;
                 continue;
             }else if(tmp == next){
                 continue;
             }else {
                 ret++;
             }
         }*/
         if(result < ret){
             result = ret;
         }
         return result;
     }
 };

 int main() {
     //int arr[] = {9,1,4,7,3,-1,0,5,8,-1,6};
     ,,,,};
     ]);
     vector<int> nums(arr, arr+len);
     Solution s;
     cout << s.longestConsecutive(nums) <<endl;
     ;
 }
67 / 67 test cases passed.
Status:

Accepted

Runtime: 16 ms

哈希map是一种关联容器,通过键值和映射值存储元素。允许根据键值快速检索各个元素。

插入数据使用 insert方法,查找则使用find方法,find方法返回unordered_map的iterator,如果返回为end()表示未查找到,否则表示查找到。boost::unordered_map是计算元素的Hash值,根据Hash值判断元素是否相同。所以,对unordered_map进行遍历,结果是无序的。

128. Longest Consecutive Sequence(leetcode)的更多相关文章

  1. [LeetCode] 128. Longest Consecutive Sequence 解题思路

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  2. [LeetCode] 128. Longest Consecutive Sequence 求最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  3. 【LeetCode】128. Longest Consecutive Sequence

    Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longest con ...

  4. Binary Tree Longest Consecutive Sequence -- LeetCode

    Given a binary tree, find the length of the longest consecutive sequence path. The path refers to an ...

  5. Java for LeetCode 128 Longest Consecutive Sequence

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  6. leetcode 128. Longest Consecutive Sequence ----- java

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  7. [leetcode]128. Longest Consecutive Sequence最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Y ...

  8. Leetcode 128. Longest Consecutive Sequence (union find)

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Y ...

  9. LeetCode 128 Longest Consecutive Sequence 一个无序整数数组中找到最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.Fo ...

随机推荐

  1. HDU 5023 A Corrupt Mayor's Performance Art(线段树区间更新)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5023 解题报告:一面墙长度为n,有N个单元,每个单元编号从1到n,墙的初始的颜色是2,一共有30种颜色 ...

  2. BZOJ4411——[Usaco2016 Feb]Load balancing

    1.题意: 给出N个平面上的点.保证每一个点的坐标都是正奇数. 你要在平面上画两条线,一条是x=a,一条是y=b,且a和b都是偶数. 直线将平面划成4个部分,要求包含点数最多的那个部分点数最少. 2. ...

  3. 面向对象的 CSS (OOCSS)

    原文链接:来自smashing magazine 译文 你是否听说过一个词语叫“内容就是王道”?作为一个 Web 开发者,我们的工作与内容创作有着频繁的联系.这是一条经常被引用,并且正确地解释了什么因 ...

  4. 新技能get——斜率优化

    好久没写博客了……我终于回来了…… dp总是令我很头疼的问题之一,然而我还是要学一下怎么优化它. 下面请看一道题吧: [bzoj3675][Apio2014]序列分割 试题描述 小H最近迷上了一个分割 ...

  5. canvas 中save和restore的用法

    在创建新的控件或修改现有的控件时,我们都会涉及到重写控件或View的onDraw方法. onDraw方法会传入一个Canvas对象,它是你用来绘制控件视觉界面的画布. 在onDraw方法里,我们经常会 ...

  6. 2016年11月2日--Window.document对象

    一.找到元素: docunment.getElementById("id"):                      根据id找,最多找一个: var a =docunment ...

  7. BZOJ 1051: [HAOI2006]受欢迎的牛

    Description 一个有向图,求所以能被别的点到达的点的个数. Sol Tarjan + 强连通分量 + 缩点. 缩点以后找强连通分量,缩点,然后当图有且仅有1个出度为1的点时,有答案. Cod ...

  8. 读书笔记-JVM

    局部变量表(虚拟机栈中的一部分)在编译期完成分配,运行期不会再改变大小: 每个方法对应一个栈帧(存储局部变量表.操作数栈.动态链接.方法出口等),栈帧被存储到虚拟机栈中,每个线程对应一个虚拟机栈,方法 ...

  9. Java获取新浪微博cookies

    import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.F ...

  10. apache virtualhost 针对ip开放访问

    http://serverfault.com/questions/246003/apache-httpd-how-can-i-deny-from-all-allow-from-subnet-but-d ...