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

147
Visualizações
Checking for duplicates within an array

I am trying to check for matching instances of arrays within a larger array. To do this, I am implementing a condition where if two of three numbers in an array match two of the three members of any of the arrays within a larger array, there is a continue statement to go back to a previous loop:

var threeSum = function (nums) {
  let result = [];
  for (let i = 0; i < nums.length - 2; i++) {
    for (let j = i + 1; j < nums.length - 1; j++) {
      loop1: for (let k = j + 1; k < nums.length; k++) {
        if (nums[i] + nums[j] + nums[k] === 0) {
          let smallArray = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
          for (let l = 0; l < smallArray.length && result[l]; l++) {
            if (
              smallArray[0] == result[l][0] &&
              smallArray[1] == result[l][2]
            ) {
              console.log("we already have this array")
              continue loop1;
            }
          }
          result.push(smallArray);
        }
      }
    }
  }
  return result;
};

Thus, for example threeSum([-1, 0, 1, 2, -1, -4]) should return [[-1, 0, 1], [-1, -1, 2]] when is instead is returning [[-1, 0, 1], [-1, -1, 2], [-1, 0, 1]]. I have checked using the console.log in the inner most conditional, and the if statement is never returning as true, so it is never entering the continue command. But the first and third arrays should meet the requirements of this, so it seems as if when checking the third array, the function should kick back the command.

I am a bit puzzled as to what is going wrong.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A single loop approach but with recursion and filtering for arrays with same values.

function threeSum(array, temp = [], sum = 0, i = 0) {
    if (temp.length === 3) return sum ? [] : [temp];

    const result = [];
    
    while (i < array.length) {
        result.push(...threeSum(array, [...temp, array[i]], sum + array[i], ++i));
    }

    return result.filter((s => a => (b => !s.has(b) && s.add(b))([...a].sort().join('|')))(new Set));
}

console.log(threeSum([-1, 0, 1, 2, -1, -4]));

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