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.
Ideas:
The idea is to have all the data in a hash table, starting with the first element in the table, looking for an element adjacent to it, until the adjacent one is found, which is the length of an adjacent number. Then repeat the above steps.
There is a key to this problem, start writing without AC, no erase hash table already found elements, data too big will tle, looked at others to find this problem. The details are not well handled.
Exercises
classSolution { Public: typedef unordered_set<int>Hash; intLongestconsecutive (vector<int> &num) {hash hash; Hash::iterator it; Hash::iterator it1; for(intI=0; I<num.size (); i++) Hash.insert (Num[i]); intresult =0; intTMP =0; intMax =0; while(!Hash.empty ()) {It=Hash.begin (); intElem = *it; TMP= elem+1; Max=1; Hash.erase (IT); while((It1=hash.find (TMP))! =Hash.end ()) {Max++; TMP++; Hash.erase (IT1); } tmp= elem-1; while((It1=hash.find (TMP))! =Hash.end ()) {Max++; TMP--; Hash.erase (IT1); } if(max>result) Result=Max; } returnresult; }};
[Leetcode] Longest consecutive Sequence