283. Move Zeroes

Description

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Solution

Solution 1

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    "use strict";
    let insertPos = 0;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i]) {
            nums[insertPos] = nums[i];
            insertPos++;
        }
    }
    while (insertPos < nums.length) {
        nums[insertPos] = 0;
        insertPos++;
    }
};

Solution 2

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    "use strict";
    let insertPos = 0;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i]) {
            let tmp = nums[insertPos];
            nums[insertPos] = nums[i];
            nums[i] = tmp;
            insertPos++;
        }
    }
};

results matching ""

    No results matching ""