Question
Solution
题目大意:将0移到最后
思路:
1. 数组复制
2. 不用数组复制
Java实现:
数组复制
public void moveZeroes(int[] nums) {
int[] arr = Arrays.copyOf(nums, nums.length);
int start = 0;
int end = nums.length - 1;
for (int i=0; i<arr.length; i++) {
int tmp = arr[i];
if (tmp == 0) {
nums[end--] = 0;
} else {
nums[start++] = tmp;
}
}
}
不用数组复制
public void moveZeroes(int[] nums) {
int start = 0;
int zeroCount = 0;
for (int i=0; i<nums.length; i++) {
int tmp = nums[i];
if (tmp == 0) {
zeroCount++;
} else {
nums[start++] = tmp;
}
}
for (int i = 0; i < zeroCount; i++) {
nums[nums.length - 1 - i] = 0;
}
}