283. Move Zeroes
Easy
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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
package leetcode.easy;
public class MoveZeroes {
public void moveZeroes1(int[] nums) {
int n = nums.length;
// Count the zeroes
int numZeroes = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
numZeroes++;
}
}
// Make all the non-zero elements retain their original order.
java.util.ArrayList<Integer> ans = new java.util.ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (nums[i] != 0) {
ans.add(nums[i]);
}
}
// Move all zeroes to the end
while (numZeroes > 0) {
ans.add(0);
numZeroes--;
}
// Combine the result
for (int i = 0; i < n; i++) {
nums[i] = ans.get(i);
}
}
public void moveZeroes2(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;
}
}
public void moveZeroes3(int[] nums) {
for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.length; cur++) {
if (nums[cur] != 0) {
int temp = nums[lastNonZeroFoundAt];
nums[lastNonZeroFoundAt] = nums[cur];
nums[cur] = temp;
lastNonZeroFoundAt++;
}
}
}
private void print_arr(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
@org.junit.Test
public void test1() {
int[] nums = { 0, 1, 0, 3, 12 };
print_arr(nums);
moveZeroes1(nums);
print_arr(nums);
}
@org.junit.Test
public void test2() {
int[] nums = { 0, 1, 0, 3, 12 };
print_arr(nums);
moveZeroes2(nums);
print_arr(nums);
}
@org.junit.Test
public void test3() {
int[] nums = { 0, 1, 0, 3, 12 };
print_arr(nums);
moveZeroes3(nums);
print_arr(nums);
}
}