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.
Example:
Input:
[0,1,0,3,12]
Output:
[1,3,12,0,0]
tag: array, two pointers
method1
两根指针法
left标识着为0的元素,right标识着非0元素,每当right指针标识非0时,就和left交换,这样保证了在原数组上交换,同时只遍历一次
public void moveZeroes(int[] nums) {
int left = 0;
int right = 0;
while (left < nums.length && nums[left] != 0) {
left++;
right++;
}
while (right < nums.length && nums[right] == 0) right++;
while (right < nums.length && left < nums.length) {
if (nums[right] != 0) {
swap(nums, left, right);
while (left < nums.length && nums[left] != 0) left++;
}
right++;
}
}
method 2
对method 1 的改进,操作次数最少
遍历时的right作为标识非0的指针,left为标示为0的指针,当nums[right] != 0时就交换,left,right会一起自增,当nums[right] = 0 时,left就会停在0的位置,right会自增到非0的位置
public void moveZeroes1(int[] nums){
for (int left = 0,right = 0; right < nums.length ; right++) {
if (nums[right] != 0){
swap(nums,left,right);
left++;
}
}
}
method 3
时间和空间都是O(n)的解法,先遍历一次记录0的个数,再遍历一次将非0的按原来的顺序放到新数组中,然后在往新数组的尾部添加0
public void moveZroes2(int[] nums){
int n = nums.length;
int numsOfZero = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) numsOfZero++;
}
Queue<Integer> stack = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (nums[i] != 0) stack.offer(nums[i]);
}
while (numsOfZero-- > 0)
stack.offer(0);
for (int i = 0; i < n; i++) {
nums[i] = stack.poll();
}
}
method 4
根据题目的意思,可以将数组分为两类,为0的情况和非0的情况,那么就可以使用两根指针,将遇到的为0的情况先全部用后面的非0数填充,最后再将lastNonZeroFoundAt之后的位置全部赋值为0
public void moveZroes3(int[] nums){
int lastNonZeroFoundAt = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
// After we have finished processing new elements,
// all the non-zero elements are already at beginning of array.
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroFoundAt; i < nums.length; i++) {
nums[i] = 0;
}
}
summary
- 暂且将该数组问题分类为"数组交换"问题,可以用两根指针法处理数组交换问题(使用交换swap)
- 同时也可以先处理一类,再处理另一类,如method4