移动零

问题陈述

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

示例:

1
2
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution{
public void moveZeros(int[] nums){
int index=0;
for(int num:nums){//将所有非零元素移到队首
if(num!=0){
nums[index++]=num;
}
}
while(index<nums.length){//剩下的就是0啦
nums[index++]=0;
}
}
}