Find two numbers that add up to a target
DSA, Easy
Which structure or algorithm, and what does it cost.
You get a list of integers nums and an integer target. Return the positions [i, j] of two different elements whose values add up to target. If no such pair exists, return []. If several pairs exist, return any one. You may not use the same position twice, but two equal values at different positions are allowed.
Examples
Input nums = [2, 7, 11, 15], target = 9
Output [0, 1]
Why because 2 + 7 = 9.
Input nums = [3, 3], target = 6
Output [0, 1]
Why because the two 3s are at different positions.
Input nums = [3, 2, 4], target = 6
Output [1, 2]
Why Position 0 alone does not count: 3 + 3 would reuse it.
Constraints
- 1 <= length of
nums<= 100,000. - Each value is between -1,000,000,000 and 1,000,000,000.
- The answer positions can be in any order.
Your answer must contain
- The simple method and why it is too slow for 100,000 items; the better method; code; time and memory cost; and a hand trace of example 1 through your code.