Two Sum
Given an integer array nums and an integer target, return the indices of the two distinct elements whose values sum to target. Each input has exactly one valid answer, and you may not use the same element twice.
Open official problem prompt ↗Find the two positions in the array whose values add up to a given target, using each position at most once.
Imagine sorting mail into a wall of pigeonholes labeled by value. For each new letter worth x dollars, you glance at hole labeled target - x; if a letter is already waiting there, you have your pair.
- Input
- nums = [2, 7, 11, 15], target = 9
- Output
- [0, 1]
- Why
- nums[0] + nums[1] = 2 + 7 = 9
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9Exactly one valid answer exists