This is the solution about Leetcode - Move Zeroes.

Description

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.

Solution

Analysis

Solution1

Maintain two pointers, one points to 0, one interate the whole array to find non zero digit to swap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution1 {
public void moveZeroes(int[] nums) {
if(nums==null || nums.length<2) return;
int left = 0,right = 0;
while(right < nums.length) {
if(nums[right]==0) {
if(nums[left]!=0) {
left = right;
}
}else {
if(nums[left] == 0) {
swap(nums,left,right);
left++;
}
}
right++;
}
}
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}

Solution2

  1. Iterate the array, find the location of first 0, maintain its index and assign the next non-zero digit to their original location one by one.
  2. Assign 0 to the remaining locations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution2 {
public void moveZeroes(int[] nums) {
if(nums==null || nums.length<2) return;
int j=0;
for(int i=0; i<nums.length; i++) {
if(nums[i] != 0) {
nums[j++] = nums[i];
}
}
for(; j<nums.length; j++) {
nums[j] = 0;
}
}
}