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. sql种类

  2. word文档的生成、修改、渲染、打印,使用Aspose.Words

    无需MS Word也可执行各种文档处理任务,包括文档的生成.修改.渲染.打印,文档格式转换和邮件合并等文档处理.

  3. PHP面试试题

    1,用PHP打印出前一天的时间,格式是2006-5-10 22:21:21echo date("Y:m:d H:i:s",strtotime("-1 day") ...

  4. 剑指Offer 替换空格

    题目描述 请实现一个函数,将一个字符串中的空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy.   思路: 替换空格,先遍历一遍记 ...

  5. BZOJ 1922: [Sdoi2010]大陆争霸

    Description 一个无向图,到一个点之前需要先到其他点,求从第一个点到第 \(n\) 点最短时间. Sol 拓扑+Dijkstra. 跑Dijkstra的时候加上拓扑序... 用两个数组表示 ...

  6. 装b指南

    提溜一个糖水黄桃罐头瓶,放在桌边,坐下以后,脖子略微后仰,翘着二郎腿,低头盯着屏幕看需求. 最好点一根烟,牌子无所谓,能冒烟就行.要得就是云山雾绕的感觉,从烟雾中眯着眼睛看出去,一副胸有成竹的样. 一 ...

  7. 3. Android程序生成步骤

      主要流程如下图所示:       所需要的工具列表 名称 功能介绍 在操作系统中的路径 aapt Android资源打包工具 ${ANDROID_SDK_HOME}/platform-tools/ ...

  8. Oauth 2.0第三方账号登录原理图

    百度.QQ等服务商

  9. css常用效果总结

    1.给input的placeholder设置颜色 .phColor::-webkit-input-placeholder { /* WebKit, Blink, Edge */ color:maroo ...

  10. 【leetcode】Scramble String

    Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two no ...