I am working through this solution that I saw in this discussion section of leetcode and am unable to grasp part of the logic. The name of the game is to move all zeros to the end of a given array in place while maintaining the order of the other numbers. The increment operator inside the index of j is where I am lost because wouldn't that place the non-zero number to the right?
var moveZeroes = function(nums) {
let j = 0
for(let i = 0; i < nums.length; i ) {
if(nums[i] !== 0) {
//storing the index we are iterating on
let n = nums[i]
//changing the index in place to 0
nums[i] = 0
//console.log(nums);
//
nums[j ] = n
console.log(nums);
}
}
return nums;
};
console.log(moveZeroes([0,1,0,3,12]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Remember that j is post-increment, so the initial value of j is used to index nums and then j is incremented. If it was j then j would be incremented first, then used.
CodePudding user response:
Try using Array.filter()
to separate zeroes (ex. num === 0
) and numbers that are not zeroes (ex. num !== 0
) into two new and separate arrays. Then use either Array.concat()
or the spread operator to merge them into a single array.
Details commented in the code below
// log() is an optional utility function that formats console logs
const log = data => console.log(`[${data}]`);
// This input array has zeroes everywhere
const numbers = [0, 1, 0, 0, 3, 0, 12];
const moveZeroes = array => {
// With the given array called "numbers"
// left = [1, 3, 13]
const left = array.filter(num => num !== 0);
// right = [0, 0, 0, 0]
const right = array.filter(num => num === 0);
// Then arrays "left" and "right" are merged
return [].concat(left, right)
};
log(moveZeroes(numbers));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Simply Remove All Zeros. Add Removed Zeros to the end.
var moveZeroes = (nums) =>
(
nums.toString().replaceAll("0,", "")
",0".repeat(("" nums).replace(/[^0]/g, "").length)
)
.split(",")
.map(Number);
console.log(moveZeroes([0, 1, 0, 0, 3, 0, 12])); //[ 1, 3, 12, 0, 0, 0, 0 ]
NOTE:
("" nums).replace(/[^0]/g,'').length
: number of 0 in the Arraynums.toString()
: To convert array to string we use or we could use the trick of concatenating with an empty string like"" nums
split(',')
: To convert string into an arraymap(Number)
: To convert an array of strings to numbers.