Leetcode longest contiguous sequence

Topic links: https://leetcode-cn.com/problems/longest-consecutive-sequence/

Subject to the effect:

  slightly.

analysis:

  Note that duplicate values, the sequence where it is blank.

code show as below:

. 1  class Solution {
 2  public :
 . 3      int longestConsecutive (Vector < int > & the nums) {
 . 4          unordered_map < int , int > M1; // save key length of the longest contiguous sequence led 
. 5          unordered_map < int , int > M2; // the length of the key is stored at the end of the longest contiguous sequence 
. 6          unordered_set < int > VIS; // check whether there have been few 
. 7          int ANS = 0 ;
 . 8          
. 9          for ( int= I 0 ; I <nums.size (); ++ I) {
 10              IF ! (vis.find (the nums [I]) = vis.end ()) Continue ;
 . 11              vis.insert (the nums [I]);
 12 is              
13 is              M1 [the nums [I]] M2 = [the nums [I]] = . 1 ;
 14              
15              iF (m2.find (the nums [I] - . 1 !) = m2.end ()) { // check if there in nums [i] - ending sequence 
16                  splice (nums [i] - 1 , the nums [I], M2, M1); // stitching 
. 17              }
 18 is              IF (m1.find (the nums [I] + 1 )! m1.end = ()) { //Check whether there is to nums [i] + 1 at the beginning of the sequence 
. 19                  splice (the nums [I], the nums [I] + . 1 , M2, M1); // stitching 
20 is              }
 21 is          }
 22 is          
23 is          for (Auto & X: M1) = ANS max (ANS, x.second);
 24          
25          return ANS;
 26 is      }
 27      
28      // spliced to the end of the sequence B and the sequence beginning with a 
29      inline void splice ( int B, int a, unordered_map < int , int > & mB of, unordered_map < int , int > &mA) {
 30          MB [A + mA [A] - 1 ] = mA [B - MB [B] + 1 ] = MB [B] + mA [A];
31          mA.erase (A);
32          mB.erase (B);
33      }
 34 };
View Code

 

Guess you like

Origin www.cnblogs.com/zaq19970105/p/11408556.html