smj007

Untitled

Jun 24th, 2023
1,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | Source Code | 0 0
  1. # Latest
  2. class Solution:
  3.     def twoSum(self, nums: List[int], target: int) -> List[int]:
  4.        
  5.         from collections import defaultdict
  6.         hashmap = defaultdict(int)
  7.  
  8.         for index, num in enumerate(nums):
  9.             if (target - num) in hashmap:
  10.                 return [hashmap[target-num], index]
  11.  
  12.             hashmap[num] = index
  13.            
  14. # Earlier
  15. class Solution:
  16.     def twoSum(self, nums: List[int], target: int) -> List[int]:
  17.        
  18.         hashset = {}
  19.        
  20.         for i, num in enumerate(nums):
  21.             if (target - num) in hashset:
  22.                 return [i, hashset[target - num]]
  23.             hashset[num] = i
  24.            
  25.            
  26. # Note that the below solution does not work since we expect both indices to be different
  27. class Solution:
  28.     def twoSum(self, nums: List[int], target: int) -> List[int]:
  29.        
  30.         from collections import defaultdict
  31.         hashmap = defaultdict(int)
  32.  
  33.         for index, num in enumerate(nums):
  34.             if (target - num) in hashmap:
  35.                 return [hashmap[target-num], index]
  36.            
  37.             hashmap[num] = index
  38.  
Advertisement
Add Comment
Please, Sign In to add comment