题目要求:
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
原题链接:请戳这里
给你一个数组,写一个方法将所有的0移动到数组末尾,同时保持数组原有的非零元素之间的顺序关系。
下面是我的代码:
public void MoveZeroes(int[] nums) {
int zero_num = 0;
for (int num : nums) {
if (num == 0)
zero_num++;// 循环遍历数组,计算数组中“0”的个数
}
int len = nums.length;
int temp = 0;
for (int i = 0; i < len; i++) {
if (nums[i] == 0) {// 循环遍历数组,找到“0”就将其移动到数组最后一位。
for (int j = i; j < len - 1; j++) {
temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
i--;// *移动后之前的元素index都会向前加了一个,所以i后退一次
if (i == len - zero_num - 1)// 当末尾全是“0”的时候就退出循环
break;
} else {
continue;
}
}
}
程序写的感觉比较麻烦,但是有几点是必须要注意的:
- 数组中零的个数,这个决定了退出便利循环的条件;
- 每次从数组中遍历得到一个零后,下次遍历要后退一个,不然会出现遗漏“0”的情况。比如:[1,2,0,0,4],当i=2的时候,将“0”移至末尾,得到[1,2,0,4,0],不后退的话,直接i++,得到i=3,即元素4进行处理了,漏掉了第二个0;
- 代码中星号位置比较关键,就是退出循环的条件和时机,当数组下表循环到除去零的个数时,则退出循环,不然后面就是死循环了。
下面是高手写的代码~请欣赏:
public void moveZeroes(int[] nums){
int index=0;
for (int i=0;i<nums.length;i++){
if (nums[i]!=0) nums[index++]=nums[i];//*
}
while(index<nums.length){
nums[index++]=0;
}
}
- 首先循环遍历数组,将数组中非零的元素一次赋值到数组前端。index使用的太好了!
- 再将数组末尾除去非零元素都赋值为0
- 太简洁了!羡慕!