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.
package leetcode;
import java.util.Arrays;
public class Move_Zeroes_283 {
public void moveZeroes(int[] nums) {
int length=nums.length;
int shuPointer=0;
int zeroPointer=0;
while (shuPointer<length && zeroPointer<length) {
while (zeroPointer<length&&nums[zeroPointer] != 0) {
zeroPointer++;
}
shuPointer = zeroPointer + 1;
while (shuPointer<length&&nums[shuPointer] == 0) {
shuPointer++;
}
if(shuPointer<length && zeroPointer<length){
nums[zeroPointer] = nums[shuPointer];
nums[shuPointer] = 0;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Move_Zeroes_283 m=new Move_Zeroes_283();
int[] a=new int[]{0, 1, 0, 3, 12};
m.moveZeroes(a);
System.out.println(Arrays.toString(a));
}
}
大神的方法很简洁。
public void moveZeroes(int[] nums) {
int j = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != 0) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}
还有:
// Shift non-zero values as far forward as possible
// Fill remaining space with zeros
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int insertPos = 0;
for (int num: nums) {
if (num != 0) nums[insertPos++] = num;
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}