Code Lab

Modo entrevista. Cronômetro de 15 min, sem dicas e sem autocompletar

Two sum

DifícilMap 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.

  • numbers holds integers, also negative ones and 0. 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 target 6 the answer is [1, 2], not [0, 0]. Two equal values at different indexes are fine: [3, 3] with target 6 gives [0, 1].
  • The array can have 200 000 items. Your code must finish in time.

Exemplos

twoSum([2, 7, 11, 15], 9)

Retorna [ 0, 1 ]

twoSum([3, 2, 4], 6)

Retorna [ 1, 2 ]

twoSum([1, 2], 10)

Retorna null

Fonte

Carregando o editor...
  1. EntradatwoSum([ 2, 7, 11, 15 ], 9)
    Esperado[ 0, 1 ]
  2. EntradatwoSum([ 3, 2, 4 ], 6)
    Esperado[ 1, 2 ]
  3. EntradatwoSum([ 1, 2 ], 10)
    Esperadonull

Os testes ocultos rodam no envio