Two Sum
Given an array of integers and a target, return the indices of the two numbers that add up to the target.
Assume exactly one solution exists. Return the two indices as a list [i, j] with i < j; the tests print them space-separated (e.g. 0 1).
Example
2,7,11,15 9
0 1
numsis the list of integers andtargetis the single integer . Positions count from : sits at index , at , at and at .- We need two different positions with . Pairing the first element with each of the others gives , and , so only the pair at positions and hits the target.
- The remaining pairs all overshoot: , , . So is the single answer the constraints promise.
- The output is the two indices, not the values and . With the smaller index first they print as
0 1. - Notice that one position can't be used twice, but equal values at different positions are fine: for with target the answer is
0 1, because the two s are separate elements.
Constraints
- 2 <= len(nums) <= 10^4
- -10^9 <= nums[i] <= 10^9
- Exactly one valid answer exists