Longest Consecutive Sequence

Question:

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.

Solution:

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int>& num) {
 4         map<int,bool> used;
 5     for(vector<int>::const_iterator iter=num.begin();iter!=num.end();iter++)
 6     {
 7         used[*iter]=false;
 8     }
 9     int longest=0;
10     for(vector<int>::const_iterator  ptr=num.begin();ptr!=num.end();ptr++)
11     {
12         if(used[*ptr])
13             continue;
14         int max_length=1;
15         used[*ptr]=true;
16         for(int j=*ptr+1;used.find(j)!=used.end();j++)
17         {
18             used[j]=true;
19             max_length++;
20         }
21         for(int j=*ptr-1;used.find(j)!=used.end();j--)
22         {
23             used[j]=true;
24             max_length++;
25         }
26         longest=max(longest,max_length);
27     }
28 
29     return longest;
30     }
31 };

Longest Consecutive Sequence_第1张图片

你可能感兴趣的:(sequence)