Leet Code 128. 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.

思路: 枚举每个点,看这个点的邻居是否存在,如果存在继续扩展。 扩展的时候记录已经访问过的点,下次就跳过。

AC代码:

#include<hash_set>
using namespace __gnu_cxx;
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size();
        if(n == 0) return 0;
        hash_set<int>s;
        hash_set<int>used;
        for(int i=0; i<n; i++)
            s.insert(nums[i]);
        int ans = 0;
        for(int i=0; i<n; i++)
        {
            if(used.count(nums[i]) > 0) continue;
            int left = nums[i];
            int right = nums[i];
            while(s.count(left))
            {
                used.insert(left);
                left--;
            }
            while(s.count(right))
            {
                used.insert(right);
                right++;
            }
            ans = max(ans, right-left-1);
        }
        return ans;
    }
};

 

posted @ 2016-03-20 12:29  Gu Feiyang  阅读(119)  评论(0)    收藏  举报