283 Move Zeroes

283. Move Zeroes

1. Question

Given an arraynums, write a function to move all0's to the end of it while maintaining the relative order of the non-zero elements.
For example, givennums = [0, 1, 0, 3, 12], after calling your function,numsshould be[1, 3, 12, 0, 0].
Note:
  1. 1.
    You must do this in-place without making a copy of the array.
  2. 2.
    Minimize the total number of operations.

2. Implementation

(1) Two Pointers
1
class Solution {
2
public void moveZeroes(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return;
5
}
6
7
int nonZeroIndex = 0;
8
9
for (int i = 0; i < nums.length; i++) {
10
if (nums[i] != 0) {
11
swap(nums, nonZeroIndex, i);
12
++nonZeroIndex;
13
}
14
}
15
}
16
17
public void swap(int[] nums, int index1, int index2) {
18
if (index1 == index2) {
19
return;
20
}
21
22
int temp = nums[index1];
23
nums[index1] = nums[index2];
24
nums[index2] = temp;
25
}
26
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(1)