Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created September 2, 2014 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/e8a34a4e0c7277d94842 to your computer and use it in GitHub Desktop.
Save xiren-wang/e8a34a4e0c7277d94842 to your computer and use it in GitHub Desktop.
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) {
int N = num.size();
if (N <= 0)
return 0;
if (N == 1)
return 1;
set<int> sInt;
for(int i=0; i<N; i++)
sInt.insert(num[i]);
set<int>::iterator it = sInt.begin();
int length = 1;
int prev = *it;
int maxLen = length;
while (it != sInt.end() ) {
if ( *it - prev == 1 )
length ++;
else {
maxLen = max(maxLen, length);
length = 1; // it itself
}
prev = *it;
++it;
}
maxLen = max(maxLen, length); //in case its always increasing
return maxLen;
/* In above case, if considering set.insert(*) is only amortized to const, but usually O(logn),
It's not absoluately o(n) algorithm.
Another idea is to insert to a hash, then search from min, to min+1, min+2 ...
This will work for many data points, not a few of them.
//build a hash table, and find min / max
//from min, try to get min+1, min+2 ... from hash, until max
int N = num.size();
int m = INT_MAX, M = INT_MIN;
unordered_set<int> hash;
// build hash
for(int i=0; i<N; i++) {
m = min(m, num[i]);
M = max(M, num[i]);
hash.insert(num[i]);
}
// search from hash
int scan = m;
int length = 1; //scan itself
int maxLen = 1;
while (scan <= M ) {
while( scan + 1 <=M && hash.find(scan+1) != hash.end() ) {
scan ++;
length ++;
if (scan > 0 && scan+1 < 0)
break;
}
// now scan+1 is not included, remember the length
maxLen = max(maxLen, length);
//get next included element
while (scan+1 <=M && hash.find(scan+1) == hash.end() ) {
if (scan > 0 && scan+1 < 0)
break;
scan ++;
}
//now scan+1 is included
scan ++;
length = 1; // scan itself
if (scan >0 && scan+1 < 0 ) //overflow
break;
}
return maxLen;
*/
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment