283.移动零
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
class Solution {
public void moveZeroes(int[] nums) {
//标记非零元素个数
int m = 0;
//标记零元素个数
int n = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i]==0) {
n++;
}
//非零元素移动到数组前端
else {
nums[m] = nums[i];
m++;
}
}
//根据零元素个数将后端元素置为0
for(int j = nums.length - n; j < nums.length; j++) {
nums[j] = 0;
}
}
}