04.Two Sum
EasyArrays// Mission briefing
Given an array of integers nums and an integer target, return the indices of two distinct elements whose values add up to target.
Each input has exactly one solution, and the same element cannot be used twice. Return the two indices in any order.
Example 1
Input: nums = [2, 7, 11, 15], target = 9 Output: [0, 1] Explanation: nums[0] + nums[1] = 2 + 7 = 9, so the answer is [0, 1].
Example 2
Input: nums = [3, 2, 4], target = 6 Output: [1, 2] Explanation: nums[1] + nums[2] = 2 + 4 = 6, so the answer is [1, 2].
Example 3
Input: nums = [3, 3], target = 6 Output: [0, 1] Explanation: nums[0] + nums[1] = 3 + 3 = 6, so the answer is [0, 1].
Note
In the Run panel, each test appears as: first line n, second line the n elements of nums, and third line target.
// Constraints
2 <= nums.length <= 10000-1000000000 <= nums[i] <= 1000000000-1000000000 <= target <= 1000000000Exactly one valid pair of distinct indices exists.
Time limit: 1s · Memory limit: 256 MB
Hint 1
For each element, determine which value would be needed to reach target.
Hint 2
Store previously visited values and their indices in a hash map.
Hint 3
Before storing nums[i], check whether target - nums[i] is already in the map.