1. 程式人生 > >[leetcode] 128. Longest Consecutive Sequence 解題報告

[leetcode] 128. Longest Consecutive Sequence 解題報告

題目連結:https://leetcode.com/problems/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.


思路:使用hash表來儲存陣列中的每一個數,每次遍歷到一個數的時候看往上找到所有連續的數最多有幾個,往下找比他小的數最多有幾個.為了避免連續的序列中的數重複查詢,在找到一個相鄰的數之後就把他從hash表中刪除,也就是一個連續的序列只會被查詢一次.因此時間複雜度為O(n).

明天就面facebook了,好緊張!求好運!

程式碼如下:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int, bool> hash;
        for(auto val: nums) hash[val] = true;
        int Max = 0;
        for(auto val: nums)
        {
            int len = 1, tem = val+1;
            while(hash.count(tem))
            {
                hash.erase(tem);
                len++, tem++;
            }
            tem = val-1;
            while(hash.count(tem))
            {
                hash.erase(tem);
                len++, tem--;
            }
            Max = max(len, Max);
        }
        return Max;
    }
};
參考:http://bangbingsyb.blogspot.com/2014/11/leetcode-longest-consecutive-sequence.html