Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Problem in returning indices of two numbers in array

I have this problem:

Given an array of integers nums and an integer target, return the indices of two numbers that add up to target.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

With the code below was able to get the values added in array using set and Map

What I need help is to return the indices

const arr = [{key1: 2}, {key1: 7}, {key1: 11}, {key1: 15}];
const k = 9;
const valueSet = new Set(arr.flatMap((x) => Object.values(x)));
const valueArray = [...valueSet];

valueArray.forEach((v1, i1) => {
    for (let i2 = i1 + 1; i2 < valueArray.length; i2++) {
        if ((v1 + valueArray[i2]) === k) {
            // Return the indices
            return valueArray[i2];
        }
    }
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You have to parse and find the combination of indexes which gives you the sum.

Below code will help you

const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];

let indices;
let isFound = false;
// valueArray.forEach((v1, i1) => {
for (let i1 = 0; i1 < valueArray.length && !isFound; i1++) {
  for (let i2 = i1 + 1; i2 < valueArray.length && !isFound; i2++) {
    if ((valueArray[i1] + valueArray[i2]) === k) {
      //Return the Indices
      indices = [i1, i2];
      isFound = true;;
    }
  }
}
console.log(indices);

about 4 years ago · Juan Pablo Isaza Relatório

0

The answer provided by Nitheesh works well. As for an explanation as to why your initial approach was not successful:

Using forEach to iterate over an array is different than using traditional for loops, in that the callback function is called for every element on the array. Using return in a forEach loop just breaks out of that particular element's callback, but not the entire iteration (hence, a return in a forEach loop behaves similarly to a continue in a for (...) loop.

You can read more about it here.

about 4 years ago · Juan Pablo Isaza Relatório

0

First you need to get the array with the values from your array with keys [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];. Then you loop the value array and return the index if the condition (nums[i] + nums[j] == target) => (7 + 2 == 9) is true.

const arr = [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];
const k = 9;
nums = arr.map((o) => {
  return Object.values(o)[0]
})

const twoSum = (nums, target) => {
    for(let i = 0; i < nums.length; i++){
        for(let j = i+1; j < nums.length; j++){
            if(nums[i] + nums[j] == target){
                return [i, j]
            }
        }
    }
};

console.log(twoSum(nums, k))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda