Original title Address
1. Plug all the elements into the collection
2. Traverse all elements, for each element, if there is not in the collection, even if there is, if any, expand to the left and right, find the longest continuous range, and at the time of each search to find the deleted. This ensures that the same sequential sequence is traversed only once, thus guaranteeing the complexity of the time.
Time complexity O (n)
Code:
1 intLongestconsecutive (vector<int> &num) {2 Set<int>record;3 intMaxLength =0;4 5 for(auto N:num)6 Record.insert (n);7 8 while(!Record.empty ()) {9 intLen =1;Ten intn = *(Record.begin ()); One record.erase (n); A for(inti = n-1; Record.find (i)! = Record.end (); i--) { -len++; - record.erase (i); the } - for(inti = n +1; Record.find (i)! = Record.end (); i++) { -len++; - record.erase (i); + } -MaxLength =Max (maxLength, Len); + } A at returnMaxLength;
leetcode#128 longest consecutive Sequence