Guest User

Untitled

a guest
Nov 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. # LeetCode--TwoSum
  2. # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
  3. # You may assume that each input would have exactly one solution, and you may not use the same element twice
  4. '''
  5. Example:
  6.  
  7. Given nums = [2, 7, 11, 15], target = 9,
  8.  
  9. Because nums[0] + nums[1] = 2 + 7 = 9,
  10. return [0, 1].
  11. '''
  12.  
  13. def twoSum(nums, target):
  14. """
  15. :type nums: List[int]
  16. :type target: int
  17. :rtype: List[int]
  18. """
  19. # Create dictionary(hash map) to store d[array_value] = its index
  20. # If multiple values are the same, append its index to d[array_val]
  21. # Complexity: O(n)
  22. d = {}
  23. for i in range(len(nums)):
  24. if nums[i] not in d.keys():
  25. d[nums[i]] = [i]
  26. else:
  27. d[nums[i]].append(i)
  28.  
  29. # Loop through d --> O(n)
  30. for k, v in d.items():
  31. # Retrieve the missing part of the sum if exists in d --> O(1)
  32. if (target - k) in d.keys():
  33. # In case of using two identical values to sum
  34. if len(v) > 1 and (target-k) == k:
  35. return [v[0], v[1]]
  36. else:
  37. return [v[0], d[target-k][0]]
Add Comment
Please, Sign In to add comment