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. javascript中对象学习

    第一篇文章: javascript中this关键字的详细解析:   http://blog.csdn.net/wyj880220/article/details/7305952 Javascript ...

  2. HDU1102--最小生成树

    Constructing Roads Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  3. Bellman_Ford

    Source:http://www.cnblogs.com/Jason-Damon/archive/2012/04/21/2460850.html 摘自百度百科 Bellman-ford算法是求含负权 ...

  4. iOS开发——UI基础-UIScrollView

    一.UIScrollView使用的步骤 1.创建UIScrollView 2.将需要展示的内容添加到UIScrollView中 3.设置UIScrollView的滚动范围 (contentSize) ...

  5. 操作PDF文件的关键技术点

    一个PDF文档从大到小可以分成如下几个要素:文档.章节.小节.段落.表格.列表. com.lowagie.text.Document表示PDF文档.必须为它创建一个PDF写入器,即com.lowagi ...

  6. Sqli-LABS通关笔录-3

    /*此时心情xxxx*/ 通过这一关卡我学习到了 1.大概的能够mysql回显错误注入的面目,可以根据报错,写出闭合语句. 加一个单引号.报错如下所示. 加了一个单引号就说 1'') LIMIT 0, ...

  7. Lucene4.1 视频学习

    1.将路径建立在内存中 Directory d = new RAMDirectiry(); 2.Filed Index(索引选项):Index.ANALYZED:进行分词和索引,适应于标题,内容等In ...

  8. buildroot 添加ssh,以及使用stftp 服务

    上一篇水了一下关于buildroot的基本操作,这一章水一下开启SSH服务以及配置sftp服务,以及静态IP的设置. 配置: make menuconfig Target packages  ---& ...

  9. Mysql报错Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

    安装mysql后,启动时候没有启动成功,查看了下日志报错如下:---------------------------------------------1   可以:初始化mysql:mysql_in ...

  10. BZOJ 2084: [Poi2010]Antisymmetry

    Sol Manacher. \(O(n)\) Manacher很简单啊.改一改转移就可以了. 然后我WA了.一开始天真的认为id只会是奇数,然后就GG. 一组 Hack 数据 3 1 0 0 然后就跳 ...