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.
Using a hash table to store the array, for the elements in the hash table, it is possible to find the adjacent element that is larger than him, and the element that is smaller than his neighbor, and then determine the longest continuous string.
In the case of the problem given in the array, for example: for 100, the first look down 99 did not find, and then look up 101 did not find, then the continuous length is 1, delete from the hash table 100; then 4, look down to find 3,2,1, No 5 is found up, then the continuous length is 4, remove 4,3,2,1 from the hash table. This looks up and down on an element that already exists in the hash table until the hashtable is empty. The algorithm is equivalent to iterating through the array again, then traversing the hash table again, complex O (n)
1 classSolution {2 Public:3 intLongestconsecutive (vector<int> &num) {4 5unordered_set<int>Hash;6unordered_set<int>:: iterator it;7 8 for(intI=0; I<num.size (); i++) Hash.insert (Num[i]);9 Ten intcount; One intresult=0; A while(!hash.empty ()) - { -Count=1; the -it=Hash.begin (); - intnum0=*it; - hash.erase (NUM0); + - intnum=num0+1; + while(Hash.find (num)! =hash.end ()) A { atcount++; - hash.erase (num); -num++; - } - -num=num0-1; in while(Hash.find (num)! =hash.end ()) - { tocount++; + hash.erase (num); -num--; the } * $ if(Result<count) result=count;Panax Notoginseng } - the returnresult; + } A};
"Leetcode" longest consecutive Sequence