Two Sum
Problem statement
The input is an integer array nums together with an integer target. Two entries of nums, at two different positions, add up to target, and no other choice of two positions does.
Return those two positions as a two-element array, lower position first. Positions start at 0. The two entries may hold the same value, but a single position cannot be counted twice.
Function
twoSum(nums: int[], target: int) → int[]Examples
Example 1
nums = [15,2,40,-3,11,8]target = 23return = [0,5]The first and last entries, 15 and 8, make 23. No other two positions do: for example 2 would need 21 and 40 would need -17, and neither is in the array.
Example 2
nums = [7,-3,8,12,8]target = 16return = [2,4]The value 8 sits at positions 2 and 4, and 8 + 8 = 16. Two equal values are allowed because they are at different positions.
Example 3
nums = [-4,9,-1,6,-10,3,-7,5]target = -2return = [6,7]-1 is half of -2, but it appears only once, so it cannot pair with itself. The pair is -7 + 5 = -2, at the last two positions.
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Only one choice of positions
p < qgivesnums[p] + nums[q] == target.