Given an array
nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
I'll share the javascript solution for the Move Zeroes problem from leetcode. It has O(n) time complexity.
Optimized for many zeroes
const snowball1 = nums => {
let i = 0;
let j = 0;
while (i<nums.length) {
if(nums[i] != 0) {
nums[j] = nums[i];
j++;
}
i++;
}
console.log(j);
nums.fill(0, j);
return nums;
}
Optimized for fewer zeroes
const snowball2 = nums => {
for(let i = nums.length; i--;){
if(nums[i]===0){
nums.splice(i,1)
nums.push(0);
}
}
return nums
}
Example
console.log(snowball1([0,0,1,0,0,3,0,12,0]));
console.log(snowball2([0,1,0,3,12]));
Result
[ 1, 3, 12, 0, 0, 0, 0, 0, 0 ] [ 1, 3, 12, 0, 0 ]
Comments
Post a Comment