This problem isn't very intuitive at first glance. However, the final idea should is very self-explanatory. You visit each element in nums, and then find it left and right neighbors and extend the length accordingly. The time complexity is O (n) If we guard from visiting the same element again.
You can implement it using a unordered_set or unordered_map.
The code is as follows. The last one was taken from this page which includes a nice explanation in the Follong answers.
1 //O (n) solution using Unordered_set2 intLongestconsecutive (vector<int>&nums) {3unordered_set<int>copy (Nums.begin (), Nums.end ());4unordered_set<int>filter;5 intLen =0;6 for(inti =0; I < nums.size (); i++) {7 if(Filter.find (nums[i])! = Filter.end ())Continue;8 intL = nums[i]-1, r = nums[i] +1;9 while(Copy.find (l)! = Copy.end ()) Filter.insert (l--);Ten while(Copy.find (r)! = Copy.end ()) Filter.insert (r++); OneLen = max (len, R-l-1); A } - returnLen; - } the - //O (n) solution using Unordered_map - intLongestconsecutive (vector<int>&nums) { -unordered_map<int,int>MP; + intLen =0; - for(inti =0; I < nums.size (); i++) { + if(Mp[nums[i]])Continue; AMp[nums[i]] =1; at if(Mp.find (Nums[i)-1) !=mp.end ()) -Mp[nums[i]] + = mp[nums[i]-1]; - if(Mp.find (Nums[i] +1) !=mp.end ()) -Mp[nums[i]] + = Mp[nums[i] +1]; -Mp[nums[i]-mp[nums[i]-1]] = mp[nums[i]];//Left boundary -Mp[nums[i] + mp[nums[i] +1]] = mp[nums[i]];//Right boundary inLen =Max (Len, Mp[nums[i]]); - } to returnLen; + } - the //O (N) super-concise solution (merging the above cases) * intLongestconsecutive (vector<int>&nums) { $unordered_map<int,int>MP;Panax Notoginseng intLen =0; - for(inti =0; I < nums.size (); i++) { the if(Mp[nums[i]])Continue; +Len = max (Len, mp[nums[i]] = mp[nums[i]-mp[nums[i]-1]] = Mp[nums[i] + mp[nums[i] +1]] = mp[nums[i]-1] + Mp[nums[i] +1] +1); A } the returnLen; +}
[Leetcode] Longest consecutive Sequence