我未必光芒万丈,但始终温暖有光。乐扣乐扣:https://leetcode-cn.com/problems/move-zeroes/
#283 移动零
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
输入: [0,1,0,3,12] 输出: [1,3,12,0,0]
方法一:覆盖
非0项直接覆盖到数组前头
遍历数组,将非0项覆盖到数组中,从头开始覆盖
所有非0项被安排到数组的前头,然后将剩下的项覆盖为0
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null){
return;
}
int j = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){ // 不为零就覆盖之前指针项
nums[j] = nums[i];
j++;
}
}
for(int i = j;i < nums.length; i++){ // 不全剩下位数
nums[i] = 0;
}
}
}
方法二:交换
i 、 j 指针初始都指向索引 0
i 指针负责扫描整个数组,遇到了非0项,就与 j 指向的项交换,不管它是否为 0
因此非 0 项被不断交换到数组的前部, 0 都跑到数组的最右
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null){
return;
}
int j = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i]!=0){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++;
}
}
}
}
JS 写法类似,在此不再给出代码。