Longest Consecutive Sequence

1.問題描述

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.

2.問題分析

題目是讓我們求一個整數數組中,存在最長連續整數序列的長度。同時要是O(n)解法。考慮到這個數組是無序的,可以考慮用unordered_map<int, bool>來作數據結構表示該整數數組中數的遍歷狀態。true爲訪問過,false爲初始態未訪問的。接下來我們只要遍歷這個無序map,對於每一個原數組中出現的數i,判斷i++/i- -是否也存在,若存在則給最長長度加1即可,同時狀態要從false修改爲訪問過的true。因此,只需要O(n)即可求解。

3.源代碼

#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;

class MySolution
{
public:
    int the_longest_consecutive(const vector<int> &num)
    {
        int longest_length = 0;
        unordered_map<int, bool> used;
        for (auto i : num)
            used[i] = false;

        for (auto i : num)
        {
            if (used[i])
                continue;

            int cur_length = 1;
            used[i] = true;

            for (int j = i + 1; used.find(j) != used.end(); j++)
            {
                cur_length++;
                used[j] = true;
            }   
            for (int j = i - 1; used.find(j) != used.end(); j--)
            {
                cur_length++;
                used[j] = true;
            }

            longest_length = max(longest_length, cur_length);
        }
        return longest_length;
    }

};

int main()
{
    vector<int> num = {100, 4, 200, 1, 3, 2};
    MySolution test;
    cout << test.the_longest_consecutive(num) << endl;
    return 0;
}

4.reference

[1]Creative Commons: http://creativecommons.org/licenses/by-nc-sa/3.0/
[2]https://github.com/soulmachine/leetcode

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章