LeetCode128:Longest Consecutive Sequence

mickole發表於2014-04-25

題目:

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.

解題思路:

考慮到題目要求的時間複雜度O(n),很自然的想到雜湊表,只有雜湊表的查詢時間為O(1)。

實現程式碼:

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;


/*
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.
*/
class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        if(num.empty())
            return 0;
        unordered_set<int> iset;
        vector<int>::iterator iter;
        for(iter = num.begin(); iter != num.end(); ++iter)
            iset.insert(*iter);
        
        int max = 0;
        for(iter = num.begin(); iter != num.end(); ++iter)
        {
            if(iset.count(*iter) == 1)
            {
                int c = 1;
                int g = *iter + 1;
                while(iset.count(g) == 1)
                {
                    iset.erase(g);//找到後記得要刪除,不然會重複做,超時 
                    c++;
                    g++;
                }
                int l = *iter - 1;
                while(iset.count(l) == 1)
                {
                    iset.erase(l);
                    c++;
                    l--;
                }
                if(max < c)
                    max = c;
                
            }
            
        }
        return max;    
    }
};
int main(void)
{
    int arr[] = {100, 4, 200, 1, 3, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<int> num(arr, arr+n);
    Solution solution;
    int max = solution.longestConsecutive(num);
    cout<<max<<endl;
    return 0;
}

相關文章