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?
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);