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

    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.

    使用容器实现。已经判断过的不用再次判断。

     1 class Solution {
     2 public:
     3     int longestConsecutive(vector<int> &num) {
     4         map<int, int> mp;
     5         for (int i = 0; i < num.size(); ++i) {
     6             mp[num[i]] = 1;
     7         }
     8         int len = 0, tmp;
     9         for (int i = 0; i < num.size(); ++i) {
    10             tmp = 1;
    11             if (mp[num[i]] == 1) {
    12                 int left = num[i] - 1;
    13                 while (mp.count(left) && mp[left] == 1) {
    14                     mp[left--] = 0;
    15                     ++tmp;
    16                 }
    17                 int right = num[i] + 1;
    18                 while (mp.count(right) && mp[right] == 1) {
    19                     mp[right++] = 0;
    20                     ++tmp;
    21                 }
    22                 len = (len > tmp) ? len : tmp;
    23             }
    24         }
    25         return len;
    26     }
    27 };
  • 相关阅读:
    这个是我得标题:1548669163
    Mahout学习
    MySQL
    Ubuntu
    java小程序100例
    java实现链表从尾部输出
    空格替换
    java 实现二维数组查找
    JAVA实现分页
    java 程序参数详解
  • 原文地址:https://www.cnblogs.com/easonliu/p/3699679.html
Copyright © 2011-2022 走看看