# 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.

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

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

``````class Solution {
public:
void moveZeroes(vector<int>& nums) {
int left = 0, right = 0;
while (right < nums.size()) {
if (nums[right]) {
swap(nums[left++], nums[right]);
}
++right;
}
}
};
``````

https://leetcode.com/discuss/59064/c-accepted-code

https://leetcode.com/discuss/70169/1ms-java-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation