[LeetCode] Longest Consecutive Sequence(DP)

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.

方法1:显然运行不是O(n)的时间复杂度,因此Time Limit Exceeded!

 class Solution {
public:
    int longestConsecutive(vector<int> &num) {   
        int len = num.size();
        if(len<=1)
            return len;
        int max = 1;
        map<int,int> m;//key is the number in num,value is the longest consecutive number from the  current key to  the bigger  
        for(int i=0;i<len;i++){
            
            if(m.empty())
                m[num[i]] = 1;
            else if(m.count(num[i]+1)!= 0)
            {
                int number = num[i];
                m[num[i]] = m[num[i]+1]+1;
                
                while(m.count(number-1)!= 0)
                {
                   m[number-1] = m[number]+1;
                   number--;  
                }
                max = max>m[number] ? max :m[number];
            }
            else{
                int number = num[i];
                m[num[i]] = 1;
                while(m.count(number-1)!= 0)
                {
                   m[number-1] = m[number]+1;
                   number--;
                }    
                max = max>m[number] ? max :m[number];
            }
               
        }//end for
        return max;
    }
};

方法2:其实和方法1一样的思想,只是用了map<int,vector<int>::iterator>来存储每个元素如果连续的话的上界或者下界,大大简化了
           方法1中的2个while循环,这就是方法2改进的地方了。

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        map<int,int> vTable;//v(x) = the max length of consecutive sequence starting from x
        map<int,vector<int>::iterator> aTable;
        for (vector<int>::iterator i = num.begin(); i!=num.end(); i++) {
            if(vTable.count(*i)) continue;      // Ignore same number
            vTable[*i]=1;
            aTable[*i]=i;                       // Initialization of new input
            if(vTable.count(*i+1)) {            // If i+1 exists
                vTable[*i] += vTable[*i+1];     // Update v(x)
                aTable[*i] = aTable[*i+1];      // Update a(x)
            }
            if(vTable.count(*i-1)) {            // If i-1 exists, same idea
                vTable[*aTable[*i-1]] += vTable[*i];
                aTable[*aTable[*i]] = aTable[*i-1];
                aTable[*aTable[*i-1]] = (vTable.count(*i+1)) ? aTable[*i] : i;
            }else aTable[*aTable[*i]] = i;
        }
        int max=0; // Find max in vTable
        map<int,int>::iterator iter ;
        for (iter = vTable.begin();iter!= vTable.end();iter++)
            if ((*iter).second>max) 
                max = (*iter).second;
        return max;
    }
};
原文地址:https://www.cnblogs.com/Xylophone/p/3879547.html