[LeetCode] 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.


class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        unordered_map<int,int> hashMap;
        for(int i=0;i<num.size();i++)
        {
            hashMap[num.at(i)]=i;
        }
        
        int maxLength=1;
        vector<int> visited(num.size(),0);
        for(int i=0;i<num.size();i++)
        {
            if(visited[i]==1) continue;
            visited[i]=1;
            
            //find whether num[i]+1 is in the array
            int number=num.at(i);
            int length=1;
            while(hashMap.find(number+1) != hashMap.end())
            {
                number++;
                visited[hashMap[number]]=1;
                length++;
            }
            
            number=num.at(i);
            while(hashMap.find(number-1) != hashMap.end())
            {
                number--;
                visited[hashMap[number]]=1;
                length++;
            }
            
            if(length > maxLength) maxLength=length;
        }
        return maxLength;
    }
};


你可能感兴趣的:([LeetCode] longest consecutive sequence)