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. python入门基础代码

    #查找index函数的帮助 help(str.index) #for循环和break语句from math import sqrtfor i in range(2,101): flag=1 k=int ...

  2. http://five-js.envylabs.com/

    一个很有意思的播报javascript最新资讯的网站http://five-js.envylabs.com/

  3. Delphi结构体的扩展,可以自动初始化,反初始化,自定义拷贝函数.

    转载:http://www.raysoftware.cn/?p=518&utm_source=tuicool 恭贺Delphi XE7诞生,Delphi XE7在编译器内部集成了我之前所实现的 ...

  4. PHP判断用户操作系统(Android,ipad,iphone,windows)

    这段脚本可以运用在:针对不同的操作系统,把用户引导向相应的网站或做相应的处理. <?php // PHP 判断客户端平台(PC.安卓.iPhone.平板) // strpos() 函数返回字符串 ...

  5. bufferedimage 转换成 inputstream并保存文件

    BufferedImage img = removeBackgroud(file);//去除重影 //bufferedimage 转换成 inputstream ByteArrayOutputStre ...

  6. 解析JSON插入数据库

    <?php header("Content-Type:text/html;charset=utf-8"); include_once('./mysql.php'); $fil ...

  7. intellij Idea快捷键

    CTRL+ALT+O  优化导入的类和包 Alt + Center  导入类,实现接口 CTRL+N   查找类CTRL+SHIFT+N  查找文件CTRL+SHIFT+ALT+N 查找类中的方法或变 ...

  8. Objective C 快速入门学习一

    Objective-C程序设计 1. 直接用Xcode作为IDE,舍弃gcc编译方面的学习.2. 入门例子:Eg:打印Hello World 控制台程序 #import<Foundation/F ...

  9. 欧洲杯 2016 高清直播 - 观看工具 UEFA-EURO-2016-Play.7z

    OnlineTV-MPlayer-nocache.exe 占 CPU 内存 较少 OnlineTV-FFPlay.exe 可截取图像 UEFA-EURO-2016-Play-v5.7z UEFA-EU ...

  10. iOS AES加密解密实现方法

    使用方法 先导入头文件 #import "NSData+AES.h" //AES测试 //用来密钥 NSString *key = "; //用来发送的原始数据 NSSt ...