Topic:

Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.

Example:

Input:,1,0,3,12 [0]

Output:,3,12,0,0 [1]

Copy the code

Description:

  1. Must operate on the original array, cannot copy additional arrays.
  2. Minimize the number of operations.

The topic

They only limit operations on the original array, but they don’t limit changing the array length.

So the easiest way to do that is to find a 0 and delete it from the array and then append a 0 to the end of the array, and that’s what they’re asking for

The topic
/ * *

 * @param {number[]} nums

 * @return {void} Do not return anything, modify nums in-place instead.

* /


var moveZeroes = function(nums{

    let index = 0.

        zoreNum = 0

    while (index < nums.length - zoreNum) {

        if (nums[index] === 0) {

            nums.splice(index, 1)

            zoreNum++

        } else {

            index++

        }

    }

}

Copy the code

Double pointer

Declare two Pointers:

  • A pointer left remains in the so-called position of the first 0 from front to back
  • In addition, the pointer right is kept in an array position from front to back 0
  • Substitution process: Replace the first encountered 0 with subsequent arrays one by one (update the index of the first 0)
var moveZeroes = function(nums{

    let len = nums.length,

        left = 0.

        right = 0;

    while (right < len) {

        if (nums[right]) {

            [nums[left], nums[right]] = [nums[right], nums[left]]

            left++

        }

        right++

    }

}

Copy the code

Blog: Front end little bookboy

Every day a daily problem, write the solution of the problem will be updated to the public account one day a big Lee column welcome to pay attention to the message

Public number: front end little bookboy