[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, int> hash;
        for(int val:nums)
            hash[val] = 1;
        int maxLen = 1;
        for(int i = 0; i< nums.size(); i++)
        {
            int val = nums[i], curLen = 1;
            while(hash.find(val+1) != hash.end())
            {
                val++;
                curLen++;
                hash.erase(val);
            }
            val = nums[i];
            while(hash.find(val-1) != hash.end())
            {
                val--;
                curLen++;
                hash.erase(val);
            }
            maxLen = max(maxLen, curLen);
        }
        return maxLen;
    }
};
参考:http://bangbingsyb.blogspot.com/2014/11/leetcode-longest-consecutive-sequence.html

你可能感兴趣的:(LeetCode,array)