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. (一)css代码积累——自己经常忘记,但是总记不住的代码

    1.透明度设置 90%透明:filter:alpha(opacity=90);-moz-opacity:0.90;-khtml-opacity: 0.90;opacity: 0.90; 80%透明:f ...

  2. 新建Oracle数据库时,提示使用database control配置数据库时,要求在当前oracle主目录中配置监听程序

    新建一个oracle数据库时,当提示使用database control配置数据库时,要求在当前oracle主目录中配置监听程序等字样的时候,问题是那个监听的服务没有启动,解决方法如下: 打开cmd命 ...

  3. HDU 3351 Seinfeld(括号匹配)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3351 解题报告:输入一个只有'{'跟'}'的字符串,有两种操作,一种是把'{'变成'}',另一种是'} ...

  4. iOS 图片 的 聊天气泡显示 Objective-C

    - (void)viewDidLoad { [super viewDidLoad]; UIImageView *ImageView01 = [[UIImageView alloc] init]; [I ...

  5. 剑指Offer 顺时针打印矩阵

    题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2, ...

  6. qt-4.8.5 显示图片居中笔记

    已经太久没有写过qt的程序了,所以导致的后果就是一个很简单的程序写了老半天还没写完整. 今天想实现的功能在原来软件的基础上显示他的版本. 因为想在该界面显示一个logo,一开始在pc机上跑发现图片一直 ...

  7. SVN迁移到Git的过程(+ 一些技巧

    关于在VCS中SVN和Git之间的迁移(Clone)这个部分网上已经有大批的文章介绍,而且都非常不错,能够满足我们的常见的需求,这里介绍的是我自己整理的一些技巧和使用中出现的一些问题和疑问.阅读本篇文 ...

  8. 读书笔记-JVM

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

  9. Glyphicons字体图标

    Glyphicons字体图标-----好处可以减少请求,容易控制样式! <p> <button type="button" class="btn btn ...

  10. Range Sum Query 2D - Mutable & Immutable

    Range Sum Query 2D - Mutable Given a 2D matrix matrix, find the sum of the elements inside the recta ...