easy
arrays
hashmap
Given an integer array nums and an integer target, return the indices of two distinct elements whose values add up to target. Exactly one valid pair exists. Return the lower index first.
Input / output
- Input:
nums: integer[],target: integer - Output:
[leftIndex, rightIndex]
Examples
nums = [2, 7, 11, 15], target = 9returns[0, 1]because2 + 7 = 9.nums = [3, 2, 4], target = 6returns[1, 2].
Constraints
2 <= nums.length <= 10,000-1,000,000 <= nums[i], target <= 1,000,000- Do not reuse the same array element.
Follow-up Can you solve it in linear time with a single pass and explain the memory tradeoff?
Examples
Example 1
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Example 2
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3
Input: nums = [3,3], target = 6
Output: [0,1]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.