move zeroes

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:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations

给定一个数组,把所有0移到数组末尾,同时保证非0数的相对顺序不变。不能使用额外的空间,且保证操作次数最小。 比如,数组[0,1,0,3,12],处理后得到的结果应该为[1,3,12,0,0]。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class  {
public void moveZeroes(int[] nums) {
int index = 0;
for (int i=0;i<nums.length;i++) {
if (nums[i]!=0) {
nums[index] = nums[i];
index++;
}
}
for (int i=index;i<nums.length;i++) {
nums[i] = 0;
}
}
}