Advertisement
nathanwailes

LeetCode 1 - Two Sum - 2023.09.29 solution

Sep 28th, 2023
1,063
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.57 KB | None | 0 0
  1. class Solution:
  2.     def twoSum(self, nums: List[int], target: int) -> List[int]:
  3.         """ Sort the array and then work inwards from the outer ends:
  4.        constant memory and nlogn time.
  5.  
  6.        Use a dict to keep track of seen numbers, and if you find a match,
  7.        return that: constant time and o(n) memory.
  8.  
  9.        """
  10.         seen_nums = dict()
  11.  
  12.         for i, num in enumerate(nums):
  13.             difference = target - num
  14.             if difference in seen_nums:
  15.                 return seen_nums[difference], i
  16.            
  17.             seen_nums[num] = i
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement