zoukankan      html  css  js  c++  java
  • 24. Longest Consecutive Sequence

    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. 利用 hash_map 结构,数组有序时查找的思想。

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            if(num.size() == 0) return 0;
            unordered_map<int, bool> _map;
            for(size_t i = 0; i < num.size(); ++i)  
                _map.insert(pair<int ,bool>(num[i], false));
            int ans = 0;
            for(auto it = _map.begin(); it != _map.end(); ++it) {
                if(it->second) continue; // visited
                int len = 1;
                int v1 = it->first-1;
                while(_map.count(v1))  { _map[v1--] = true; len++; }
                int v2 = it->first+1;
                while(_map.count(v2)) { _map[v2++] = true; len++; }
                if(len > ans) ans = len;
            }
            return ans;
        }
    };
    

     2. 动态的构造线段(两端为线段始末位置),这样从一端点可获取另一端点位置。若当前点可增加有向线段长度,拓展线段。

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            int answer = 0;
            unordered_map<int ,int>_map;
            int low, high;
            for(int i = 0; i < num.size(); ++i) {
                if(_map.count(num[i])) continue; // must be used.
                _map[num[i]] = num[i];
                low = high = num[i];
                if(_map.count(num[i]-1)) low = _map[num[i]-1];
                if(_map.count(num[i]+1)) high = _map[num[i]+1];
                answer = max(answer, high - low + 1);
                if(low == high) continue;// not in a line
                _map[low] = high;
                _map[high] = low;
            }
            return answer;
        }
    };
    
  • 相关阅读:
    Oracle的列操作(增加列,修改列,删除列),包括操作多列
    txt文本怎么去除重复项
    Javascript去掉字符串前后空格
    Js作用域链及变量作用域
    js变量以及其作用域详解
    如何在sqlserver 的函数或存储过程中抛出异常。
    存储过程如何处理异常
    设置VS2010和IE8 调试ATL控件<转>
    YUV图像合成原理<转>
    VS2013 查看程序各个函数的CPU利用率<转>
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3938543.html
Copyright © 2011-2022 走看看