───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───
Problem
- Given an array of integers
numsand an integertarget, return the indicesiandj, such thatnums[i] + nums[j] == targetandi != j. - You may assume that every input has exactly one pair of indices
iandjthat satisfy the condition. - Return the answer with the smaller index first.
Solution
- Two loops work, but slow (
O(n^2)). - Instead, solve with a hashmap that has the seen numbers (
O(n)) as a key, and the index as a value.- Then, we loop and check if the complement of
nexists in the hashmap. If so, return the two indices.
- Then, we loop and check if the complement of
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# time complexity: O(n)
# space complexity: O(n)
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───