题目名称

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例

输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

题解

将数组的每一位与前一位 0 进行位置互换

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let zeroL = 0
for(let i = 0; i < nums.length; i++) {
if(nums[i] !== 0) {
for(let j = i; j > 0; j--) {
if(nums[j - 1] === 0) {
[nums[j], nums[j-1]] = [nums[j-1], nums[j]]
} else {
break;
}
}
} else {
zeroL++
}
}
};