Find Pair With Target Sum
- Array
- Hash Map
Given an array of integers nums and an integer target, return the indices of two different elements whose values add up to target. You may assume that every input has exactly one valid answer. You cannot use the same array element twice.
Return the two indices in ascending order.
Pair with a negative value
- Input
"nums": [12, -5, 9, 21], "target": 16
- Output
[1, 3]
Explanation: The values -5 and 21 form the only pair whose sum is 16.
Separated matching values
- Input
"nums": [8, 14, -2, 30, 5], "target": 19
- Output
[1, 4]
Explanation: Indices 1 and 4 contain 14 and 5, which add up to 19.
Constraints
2 <= nums.length <= 10,000-1,000,000 <= nums[i] <= 1,000,000-2,000,000 <= target <= 2,000,000- Exactly one valid pair exists.
Follow-up
Can you solve the problem in O(n) time using a hash map?