File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ import  scala .collection .mutable 
2+ 
3+ object  Solution  {
4+   def  twoSum (nums : Array [Int ], target : Int ):  Array [Int ] =  {
5+     val  numsWithIndex  =  nums.zipWithIndex
6+     val  targets  =  numsWithIndex.toMap
7+ 
8+     def  compliment (v : Int ):  Option [Int ] =  targets.get(target -  v)
9+ 
10+     numsWithIndex
11+       .find { case  (v, i) =>  ! compliment(v).forall(_ ==  i) }
12+       .map { case  (v, i) =>  Array (i, compliment(v).get) }
13+       .orNull
14+   }
15+ 
16+   /**  
17+    * Optimization of above solution to do it in "one pass" 
18+    * i.e. build the map as we traverse the input collection 
19+    */  
20+   def  twoSumOnePass (nums : Array [Int ], target : Int ):  Array [Int ] =  {
21+     val  targets  =  mutable.Map [Int , Int ]()
22+ 
23+     for  ((v, i) <-  nums.zipWithIndex) {
24+       val  answer  =  targets.get(target -  v).map(Array (_, i))
25+       
26+       if  (answer.nonEmpty)
27+         return  answer.get
28+ 
29+       targets.put(v, i)
30+     }
31+ 
32+     null 
33+   }
34+ }
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments