Two Sum
Problem statement
Given an integer array nums and an integer target, return the indices of the two distinct elements whose sum equals target.
Exactly one unordered pair of indices is a solution. Return its two zero-based indices in increasing order. The same array position cannot be used twice.
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 add to 9.
Example 2
nums = [3,2,4]target = 6return = [1,2]The two different positions containing 2 and 4 add to 6.
Constraints
- 2 ≤ nums.length ≤ 10,000.
- −100,000,000 ≤ nums[i], target ≤ 100,000,000.
- Exactly one pair of distinct indices has the required sum.