【LeetCode 128 Longest Consecutive Sequence】

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Solution1:(朴实的Hash想法,空间复杂度。。。过大)

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int maxVal = INT_MIN, minVal = INT_MAX;
        int len = nums.size();
        int count = 0;
        
        if(len > 0){
            for(int i = 0; i < len; i++){
                maxVal = max(maxVal, nums[i]);
                minVal = min(minVal, nums[i]);
            }
            int hashT[maxVal-minVal+1];
            for(int i = 0; i < maxVal-minVal+1; i++)
                hashT[i] = 0;
            for(int i = 0; i < len; i++){
                hashT[nums[i]-minVal] = 1;
            }
            
            for(int i = 0; i < maxVal-minVal+1; i++){
                if(hashT[i] == 1){
                    int curCount = 1;
                    int j = i+1;
                    while(j < maxVal-minVal+1 && hashT[j] == 1){
                        curCount++;
                        j++;
                    }
                    count = max(count, curCount);
                    i = j;      
                }
            }
        }
        
        return count;
        
    }
};

Solution2:unordered_map【正确解法】

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        map<int, int> hashT;
        int maxSubseq = 0;
        int len = nums.size();
        
        if(len > 0){
            for(int i = 0; i < len; i++){
                auto it = hashT.find(nums[i]);
                if(it != hashT.end())
                    continue;
                auto it1 = hashT.find(nums[i]-1);
                auto it2 = hashT.find(nums[i]+1);
                
                int left = ( it1 == hashT.end() ? 0 : hashT[nums[i]-1] );
                int right = ( it2 == hashT.end() ? 0: hashT[nums[i]+1] );
                
                int curLen = left + right + 1;
                hashT[nums[i]] = curLen;
                
                hashT[nums[i]-left] = curLen;
                hashT[nums[i]+right] = curLen;
                maxSubseq = max(maxSubseq, curLen);
                
            }
        }
        return maxSubseq; 
    }
};

unordered_map理论上应该更快,但OJ上反而慢了不少??O(n)的时间复杂度证明?

猜你喜欢

转载自blog.csdn.net/lqy0927/article/details/82114415