给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
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.
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
//for循环
var moveZeroes = function (nums) {
if (nums.length == 0) {
return
}
var j = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
[nums[i], nums[j]] = [nums[j], nums[i]];
j++
}
}
};
//while 循环
var moveZeroes = function (nums) {
if (nums.length == 0) {
return
}
var i = 0;
var j = 0;
while (i < nums.length) {
if (nums[i] != 0) {
[nums[i], nums[j]] = [nums[j], nums[i]]; //交换顺序
i++;
j++;
} else {
i++;
}
}
};
采用双指针
碰到非零项,两个指针对应的值进行交换,每交换一次j自加一------j指针向前移一个
碰到0的时候,i自加一,j指针不变,此时j指针指向的是0,直到i指针指向非0的时候进行交换,此时就将0转换到后面,以此类推,最后将0全部换到了最后。