Two Sum
Problem statement
Given an integer array nums and an integer target, return the zero-based indices of the two numbers whose sum is target.
Use two different positions. Return the smaller index first. Exactly one valid pair exists.
Function
twoSum(nums: int[], target: int) → int[]Examples
Example 1
nums = [2,7,11,15]target = 9return = [0,1]The values at indices 0 and 1 are 2 and 7. Their sum is 9, so return [0,1].
Example 2
nums = [3,2,4]target = 6return = [1,2]The values 2 and 4 sum to 6. They are at indices 1 and 2. The single value 3 cannot be used twice.
Constraints
2 <= nums.length <= 2000-1000000 <= nums[i] <= 1000000-2000000 <= target <= 2000000- Exactly one pair of distinct indices sums to the target.