题目描述

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, 1, 0, 3, 12
^^
ij

0, 1, 0, 3, 12
^  ^
i  j

1, 1, 0, 3, 12
^  ^
i  j

1, 1, 0, 3, 12
^     ^
i     j

1, 3, 0, 3, 12
^     ^
i     j

1, 3, 12, 3, 12
^     ^
i     j

1, 3, 12, 0, 12
^  ^
i  j

1, 3, 12, 0, 0
^ ^
i j

output: [1, 3, 12, 0, 0]``````

Python

``````class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = 0
for num in nums:
if num != 0:
nums[i] = num
i += 1
while i < len(nums):
nums[i] = 0
i += 1``````

Java

``````public class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
for (int num : nums) {
if (num != 0) {
nums[i] = num;
i++;
}
}
while (i < nums.length) {
nums[i] = 0;
i++;
}
}
}``````

C++

``````class Solution {
public:
void moveZeroes(vector<int> &nums) {
int i = 0;
for (auto num : nums) {
if (num != 0) {
nums[i] = num;
i++;
}
}
while (i < nums.size()) {
nums[i] = 0;
i++;
}
}
};``````