Leetcode problem 15 - Move Zeroes
Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2:
Input: nums = [0] Output: [0]
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
let isNotZero = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[isNotZero] = nums[i];
isNotZero++;
}
}
for (let j = isNotZero; j < nums.length; j++) {
nums[j] = 0;
}
};
The function then iterates through the nums
array using a for
loop. For each element that is non-zero, it moves the element to the position indicated by isNotZero
and increments isNotZero
.
After iterating through the entire array, all non-zero elements are moved to the front of the array, while maintaining their relative order. To fill the remaining positions with zeroes, the function uses a second for
loop starting from isNotZero
and sets all elements to 0, effectively moving all zeroes to the end of the array.
Leave a comment