解法一:
public void moveZeroes(int[] nums) {
if (nums.length==1) {
return;
}
int zeroNum=0;
for (int i = 0; i < nums.length-zeroNum; i++) {
if (nums[i]==0) {
for (int j = i+1; j < nums.length; j++) {
nums[j-1] = nums[j];
}
zeroNum++;
nums[nums.length-zeroNum] = 0;
i = i-1;
}
}
}
解法二(感觉 for (int i = 0; i < nums.length; i++) 开销比foreach小):
public class solution {
<span style="white-space:pre"> </span> public void moveZeroes(int[] nums) {
<span style="white-space:pre"> </span> int ptr = 0;
<span style="white-space:pre"> </span> for (int i = 0; i < nums.length; i++) {
<span style="white-space:pre"> </span>if (nums[i]!=0) {
<span style="white-space:pre"> </span>nums[ptr++] = nums[i];
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span> while (ptr<nums.length) {
<span style="white-space:pre"> </span>nums[ptr++] = 0;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span> }
}