[leetcode] problem 283 – 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.

Example

Input: [0,1,0,3,12]

Output: [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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void (int[] nums) {
int start = 0;
int end = 0;

while (end < nums.length) {
if (nums[end] != 0) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
}

end++;
}
}