题目描述
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]
题解
/**
* 快慢指针
* 快指针用于遍历数组
* 慢指针用于指向下一个被替换/覆盖的元素,即0元素
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
const len = nums.length
if (len <= 1) return len
let slow = 0, fast = 0
while (fast < len) {
if (nums[fast]) {
slow !== fast && ([nums[slow], nums[fast]] = [nums[fast], nums[slow]])
slow ++
}
fast ++
}
};
/**
* 要求原址操作,思路是拿到所有非0数组和0数组,清空原数组,最后根据非0数组和0数组按顺序生成新数组
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
if (!nums.some(v => v !== 0)) return nums
const zeros = nums.filter(v => v === 0)
const notZeros = nums.filter(v => v !== 0)
nums.length = 0
nums.push(...notZeros, ...zeros)
return nums
};
/**
* 要求原址操作,思路是拿到所有非0数组,覆盖原数组,最后根据原数组长度填0
* 优点是节省了空间,没有额外开辟数组
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
if (!nums.some(v => v !== 0)) return nums
const nonZeros = nums.filter(v => v !== 0)
for (let index = 0; index < nums.length; index++) {
nums[index] = nonZeros[index] || 0
}
return nums
};
/**
* 要求原址操作,思路维持一个指针k, k永远指向当前数组第一个0元素,从而保证[0,k)中所有元素为非0元素
* 优点是节省了空间,没有额外开辟数组
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
for (let index = 0, k = 0; index < nums.length; index++) {
if (nums[index]) {
index !== k && ([nums[index], nums[k]] = [nums[k], nums[index]])
k++
}
}
return nums
};