File tree Expand file tree Collapse file tree 1 file changed +26
-27
lines changed Expand file tree Collapse file tree 1 file changed +26
-27
lines changed Original file line number Diff line number Diff line change 1- var  nextGreaterElement  =  function ( nums1 ,  nums2 )  { 
2-     // O (n + m) 
3-     let  nums1Idx  =  new  Map ( ) ;  { 
4-         let  idx  =  0 ; 
5-         for ( const  n  of  nums1 ) 
6-             nums1Idx . set ( n ,  idx ++ ) ; 
7-     } 
8-     let  res  =  [ ] ; 
9-     for ( let  i  =  0 ;  i  <  nums1 . length ;  i ++ ) 
10-         res . push ( - 1 ) ; 
11-     
12-     let  stack  =  [ ] ; 
13-     for ( let  i  =  0 ;  i  <  nums2 . length ;  i ++ )  { 
14-         let  cur  =  nums2 [ i ] ; 
15-         
16-         // while stack is not empty and current is greater than the top of the stack 
17-         while ( stack . length  >  0  &&  cur  >  stack [ stack . length  -  1 ] )  { 
18-             let  val  =  stack . pop ( ) ; 
19-             let  idx  =  nums1Idx . get ( val ) ; 
20-             res [ idx ]  =  cur ; 
21-         } 
22-         
23-         if ( nums1Idx . has ( cur ) ) 
24-             stack . push ( cur ) ; 
25-     } 
26-     
27-     return  res ; 
1+ /** 
2+  * HashMap and Stack 
3+  * Time O(N + M) | Space O(N) 
4+  * https://leetcode.com/problems/next-greater-element-i 
5+  * @param  {number[] } nums1 
6+  * @param  {number[] } nums2 
7+  * @return  {number[] } 
8+  */ 
9+ 
10+ var  nextGreaterElement  =  function  ( nums1 ,  nums2 )  { 
11+ 	const  subsetMap  =  new  Map ( nums1 . map ( ( val ,  i )  =>  [ val ,  i ] ) ) ; 
12+ 	const  res  =  new  Array ( nums1 . length ) . fill ( - 1 ) ; 
13+ 
14+ 	let  stack  =  [ ] ; 
15+ 
16+ 	for  ( let  num  of  nums2 )  { 
17+ 		while  ( stack . length  &&  num  >  stack . at ( - 1 ) )  { 
18+ 			const  val  =  stack . pop ( ) ; 
19+ 			const  idx  =  subsetMap . get ( val ) ; 
20+ 			res [ idx ]  =  num ; 
21+ 		} 
22+ 
23+ 		if  ( subsetMap . has ( num ) )  stack . push ( num ) ; 
24+ 	} 
25+ 
26+ 	return  res ; 
2827} ; 
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments