LeetCode OJ:Longest Consecutive Sequence

Longest Consecutive Sequence

  Total Accepted: 4795  Total Submissions: 18202 My Submissions

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.

O(nlogn)复杂度即先排序的实现如下,虽然AC,但不满足题目要求

class Solution{
public:
	int longestConsecutive(vector<int> &num){
		sort(&num[0],&num[0]+num.size());
		int maxV=1;
		int count=1;
		for(int i=1;i<num.size();i++){
		    if(num[i]==num[i-1])continue;
			if(num[i]-num[i-1]==1){
				count++;
			}
			else{
				maxV=maxV<count?count:maxV;
				count=1;
			}
		}
		return maxV<count?count:maxV;
	}
};

O(n)时间复杂度

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


你可能感兴趣的:(LeetCode)