Title link: leetcode-cn.com/problems/mo…

Solution:

Or fast or slow pointer method

We’re going to do what we did before

Fast Pointers find non-zero, slow Pointers store non-zero

When the fast pointer finds a non-zero value, it tells the slow pointer to save it. When the slow pointer finishes saving, it moves forward and waits for the next one

After the fast pointer traverses the array, everything in the array before the slow pointer index is sorted, and everything after the slow pointer index (including itself) is 0, so set everything after that to 0

/* * @lc app=leetcode.cn id=283 lang=javascript * * [283] move zero */

// @lc code=start
/ * * *@param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function (nums) {
  if (nums.length < 1) return nums;
  let slow = 0,
    fast = 0;
  while (fast < nums.length) {
    // If the fast pointer finds a non-zero value, tell the slow pointer to save it
    if(nums[fast] ! = =0) {
      nums[slow] = nums[fast];
      // After the slow pointer is saved, step forward and prepare to save the next one.
      slow++;
    }
    fast++;
  }
  // After the fast pointer traverses the array, everything before nums[slow] is sorted, and everything after nums[slow] (including nums[slow]) is set to 0
  while (slow < fast) {
    nums[slow] = 0;
    slow++;
  }
  return nums;
};
// @lc code=end

Copy the code