Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
¿Encontrar el par de suma de los elementos dentro de la matriz?

Haga que la función ArrayChallenge(arr) tome la matriz de enteros almacenados en arr y determine si dos números (excluyendo el primer elemento) en la matriz pueden sumar el primer elemento de la matriz. Por ejemplo: si arr es [7, 3, 5, 2, -4, 8, 11], entonces en realidad hay dos pares que suman el número 7: [5, 2] y [-4, 11]. Su programa debe devolver todos los pares, con los números separados por una coma, en el orden en que aparece el primer número en la matriz. Los pares deben estar separados por un espacio. Entonces, para el ejemplo anterior, su programa devolvería: 5,2 -4,11

Si no hay dos números que sumen el primer elemento de la matriz, devuelva -1

 Input: [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7] Output: 6,11 10,7 15,2 Final Output: --6--,--1----1-- --1--0,7 --1----5--,2 Input: [7, 6, 4, 1, 7, -2, 3, 12] Output: 6,1 4,3 Final Output: --6--,--1-- 4,3

Mi acercamiento

 function ArrayChallenge(arr) { var sum = [] for (var i = 0; i < arr.length; i++){ for (var j = i + 1; j < arr.length; j++){ if(arr.[i] + arr[j]=== ) } } // code goes here return arr; } // keep this function call here console.log(ArrayChallenge(readline()));

¿Puedes ayudarme con esto?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Lógica

  • Bucle a través de la matriz.
  • Comience desde el índice 1 hasta el último nodo (excepto el índice 0) en el ciclo externo.
  • Srart desde un nodo al lado del bucle exterior en el bucle interior.
  • Compruebe la suma de ambos nodos.
  • Si el valor de la suma es el mismo que el nodo en el primer índice, insértelo en la matriz de suma en el formato requerido.
  • Compruebe la longitud de la matriz de suma. Si longitud> 0, la matriz de suma de unión y retorno. De lo contrario, devuelve -1

Código de trabajo

 const input = [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]; const input2 = [7, 6, 4, 1, 7, -2, 3, 12]; const input3 = [37, 6, 4, 1, 7, -2, 3, 12]; function ArrayChallenge(arr) { var sum = [] for (var i = 1; i < arr.length; i++) { for (var j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] === arr[0]) { sum.push([arr[i], arr[j]].join()); } } } return sum.length > 0 ? sum.join(" ") : -1; } console.log(ArrayChallenge(input)); console.log(ArrayChallenge(input2)); console.log(ArrayChallenge(input3));

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar un reductor seguido de un bucle forEach para empujar los pares a una matriz vacía y luego unirlos al final.

 const ArrayChallenge = (nums) => { const pairs = [] // Get the first and remove it from the array const first = nums.splice(0, 1)[0] nums.reduce((all, curr) => { all.forEach((a) => { // Check if we have a match if (curr + a === first) { // check if it's already in the array // we don't want duplicates if (pairs.indexOf(`${a},${curr}`) === -1 && pairs.indexOf(`${curr},${a}`) === -1) { // push the pair to the array separated by a space pairs.push(`${curr},${a}`) } } }) return all }, nums) // we pass in nums as the starting point // If there are no pairs then return -1 if (pairs.length === 0) { return -1 } else { // Join the pairs together with a space const result = pairs.join(' ') // Replace each digit (\d) with hyphens before and after const parsed = result.replace(/(\d)/g, '--$1--') return parsed } } const result1 = ArrayChallenge([17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]) console.log(result1) const result2 = ArrayChallenge([7, 6, 4, 1, 7, -2, 3, 12]) console.log(result2)

about 4 years ago · Juan Pablo Isaza Report

0

Su enfoque utiliza una complejidad de nivel O (n ^ 2). Esto se puede resolver usando O (n) si está dispuesto, así que sacrifique un poco la complejidad del espacio.

Lo que puedes hacer es:

  1. Haz un objeto vacío.
  2. almacene todos los valores de la matriz (no el elemento 0) en el objeto como clave y agregue su valor como verdadero.
  3. Haga un bucle en la matriz (desde el 1er índice). Tome el valor y réstelo del elemento 0. encuentre este valor restado del objeto, si no devuelve indefinido, haga un par y guárdelo.

Una desventaja de este método es que encontrará entradas duplicadas en el resultado. Este enfoque utiliza la complejidad del tiempo O(n) y la complejidad del espacio O(n)

 function ArrayChallange(arr) { let numObj = {} let i = 1 let result = [] let tempVal // Pushing all elements of arr (from index 1) inside numObj while(i<arr.length){ numObj[arr[i]] = true } i = 1 // Looping the array to find pairs while(i < arr.length){ tempVal = numObj[Math.abs(arr[0] - arr[i])] if(tempVal){ result.push(arr[i].toString() +","+tempVal.toString()) } } if(result.length !== 0) return result.join(" ") else return -1 }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!