283. Move Zeroes
Description
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]
Constraints:
1 <= nums.length <= 10^4
2^31 <= nums[i] <= 2^31 - 1
My Solution #1
// Not quite accurate solution
// need to use two pointers to solve this problem
// Also bigO is O(n^2) (splice method is O(n) and the for loop is O(n))
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
for(let i = nums.length - 2; i >= 0; i--) {
if(nums[i] === 0) {
nums.splice(i,1);
nums.push(0);
}
}
};
My Solution #2
// More accurate solution using two pointers
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
let i = 0;
let j = 1;
while (j < nums.length) {
// if the first pointer is not 0, move to the next element
if(nums[i] !== 0) {
i++;
j++;
} else {
// if the first pointer is 0 and the second pointer is not 0, swap the elements
if(nums[j] !== 0) {
[nums[i], nums[j]] = [nums[j], nums[i]];
i++;
}
// if the second pointer is 0, move to the next element
j++;
}
}
}