Two Sum
Examples
Example 1:
Input: nums = [3,4,5,6], target = 7
Output: [0,1]
Explanation:
Example 2:
Input: nums = [4,5,6], target = 10
Output: [0,2]
Example 3:
Input: nums = [5,5], target = 10
Output: [0,1]
Example 1:
Input: nums = [3,4,5,6], target = 7
Output: [0,1]
Explanation:
Example 2:
Input: nums = [4,5,6], target = 10
Output: [0,2]
Example 3:
Input: nums = [5,5], target = 10
Output: [0,1]
Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.
You may assume that every input has exactly one pair of indices i and j that satisfy the condition.
Return the answer with the smaller index first.
nums[0] + nums[1] == 7, so we return [0, 1].
2 <= nums.length <= 1000-10,000,000 <= nums[i] <= 10,000,000-10,000,000 <= target <= 10,000,000Scan the array while keeping a hash map from value to its index. For each number, compute the complement target - num and check if it has been seen; if so, return the stored index and the current index. This naturally handles duplicates and negative values, and returns indices in increasing order because the stored index is always from an earlier position.
At any position i), the map contains exactly the indices of all earlier elements. If nums[i]completes a valid pair with some earliernums[j], then the complement lookup finds jand we return[j, i]`. The problem guarantees exactly one solution, so the first such match is correct.
O(n)O(n)class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []