Mode entretien. Minuteur de 15 min, sans indices ni autocomplétion
Two sum
DifficileMap and Set15 min
Write a function twoSum(numbers, target) that finds two different items of the array numbers that add up to target, and returns their indexes as [i, j] with i < j. If there is no such pair, return null.
numbersholds integers, also negative ones and0. The same value can appear more than once.- At most one pair adds up to
target, so the answer is never ambiguous. - "Two different items" means two different indexes: in
[3, 2, 4]with target6the answer is[1, 2], not[0, 0]. Two equal values at different indexes are fine:[3, 3]with target6gives[0, 1]. - The array can have 200 000 items. Your code must finish in time.
Exemples
twoSum([2, 7, 11, 15], 9)Renvoie [ 0, 1 ]
twoSum([3, 2, 4], 6)Renvoie [ 1, 2 ]
twoSum([1, 2], 10)Renvoie null
Chargement de l'éditeur...
- Entrée
twoSum([ 2, 7, 11, 15 ], 9)Attendu[ 0, 1 ] - Entrée
twoSum([ 3, 2, 4 ], 6)Attendu[ 1, 2 ] - Entrée
twoSum([ 1, 2 ], 10)Attendunull
Les tests cachés se lancent à la soumission