zoukankan      html  css  js  c++  java
  • Longest Consecutive Sequence [LeetCode]

    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.

    Summary: The key idea is using hash map to record every number and their index.

     1     int longestConsecutive(vector<int> &num) {
     2         unordered_map<int, int> num_idx;
     3         for(int i = 0; i < num.size(); i ++) {
     4             num_idx[num[i]] = i;
     5         }
     6         
     7         vector<bool> visited;
     8         for(int i = 0; i < num.size(); i ++) {
     9             visited.push_back(false);
    10         }
    11         
    12         int longest_len = 0;
    13         for(int i = 0; i < num.size(); i ++) {
    14             if(visited[i] == true)
    15                 continue;
    16                 
    17             int tmp_len = 1;
    18             visited[i] = true;
    19             //increase
    20             int value = num[i] + 1;
    21             while(num_idx.find(value) != num_idx.end()){
    22                 int index = num_idx[value];
    23                 value ++;
    24                 visited[index] = true;
    25                 tmp_len ++;
    26             }
    27             //decrease
    28             value = num[i] - 1;
    29             while(num_idx.find(value) != num_idx.end()){
    30                 int index = num_idx[value];
    31                 value --;
    32                 visited[index] = true;
    33                 tmp_len ++;
    34             }
    35             
    36             if(tmp_len > longest_len){
    37                 longest_len = tmp_len;
    38                 if(longest_len > num.size() / 2)
    39                     break;
    40             }
    41         }
    42         
    43         return longest_len;
    44     }
  • 相关阅读:
    SQLAlchemy使用说明之ORM
    Python日志模块logging
    Python正则表达式模块re
    group by 小结
    Hive Beeline 官方文档学习
    在MySQL中创建cm-hive使用的数据库及账号
    MySQL导入数据错误error: 13 及解决办法
    Yum 安装并设置 MySQL
    使用xshell5 从CentOS主机download资料
    Bootstrap 学习
  • 原文地址:https://www.cnblogs.com/guyufei/p/3414035.html
Copyright © 2011-2022 走看看