Two Sum
Problem statement
Given an integer array nums and an integer target, return the two distinct indices whose values add up to target.
Exactly one valid pair exists. Return the smaller index first.
Function
twoSum(nums: int[], target: int) → int[]Examples
Example 1
nums = [2,7,11,15]target = 9return = [0,1]nums[0] + nums[1] = 2 + 7 = 9.
Example 2
nums = [3,2,4]target = 6return = [1,2]nums[1] + nums[2] = 2 + 4 = 6.
Example 3
nums = [3,3]target = 6return = [0,1]The two equal values occur at distinct indices.
Constraints
2 <= nums.length <= 10000.-1000000000 <= nums[i], target <= 1000000000.- Exactly one valid answer exists.
Source note: Author-written prompt excerpt retained for source fidelity.