Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
distinct integers in JavaScript

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). Example 1: Input: nums = [0,2,1,5,3,4] Output: [0,1,2,4,5,3]

    nums = [0,2,1,5,3,4]
var buildArray = function(nums) {
    return nums.map(n => nums[n]);
};
console.log(buildArray(nums))

can any one explain dry run of this and why it is giving output as shown above and what is distinct integers?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Maybe this example will help you understand what is going on in the code. All examples will produce same result. In the example using map, n is equivalent to nums[i].

const nums = [0, 2, 1, 5, 3, 4];

// Using Array.map()
var buildArray = function(nums) {
  return nums.map(n => nums[n]);
};
console.log('Using Array.map() : ', buildArray(nums))

// Using Array.map() with index
var buildArray2 = function(nums) {
  return nums.map((n, i) => nums[nums[i]]);
};
console.log('Using Array.map() with index : ', buildArray2(nums))

// Using For Loop
let ans = new Array(nums.length);
for (let i = 0; i < nums.length; i++) {
  ans[i] = nums[nums[i]];
}
console.log('Using for loop : ', ans);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda