找出最大连续自然数个数

http://blog.csdn.net/xiajun07061225/article/details/870627


http://oj.leetcode.com/problems/longest-consecutive-sequence/

class Solution
{
public:
    int longestConsecutive(vector<int> const& num)
    {
        unordered_map<int, bool> used;
        for (auto i : num) 
            used[i] = false;
        int longest = 0;
        for (auto i : num)
        {
            if (used[i]) continue;
            int length = 1;
            used[i] = true;
            for (int j = i + 1; used.find(j) != used.end(); ++j)//向右试探
            {
                used[j] = true;
                ++length;
            }
            for (int j = i - 1; used.find(j) != used.end(); --j)//向左试探
            {
                used[j] = true;
                ++length;
            }
            longest = max(longest, length);
        }
        return longest;
    }
};


你可能感兴趣的:(找出最大连续自然数个数)