Two Sum
EasyArrays & Hashing · Amazon
Given an integer array nums and an integer target, return the indices of two different positions whose values add up to target.
- Every input has exactly one such pair of positions.
- You may not use the same position twice, but two different positions may hold equal values.
- Return the two indices as a list, in either order.
Example 1
- Input:
- nums = [4,11,2,7], target = 9
- Output:
- [2,3]
- Explanation
nums[2]is 2 andnums[3]is 7, and 2 + 7 = 9. 4 + 11 and other pairs miss the target.
Example 2
- Input:
- nums = [6,1,6], target = 12
- Output:
- [0,2]
- Explanation
- Positions 0 and 2 both hold 6, and 6 + 6 = 12. Using index 0 twice would not be allowed.
Example 3
- Input:
- nums = [-3,4,3,90], target = 0
- Output:
- [0,2]
- Explanation
- -3 + 3 = 0, using indices 0 and 2.
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Exactly one valid answer exists