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:
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
实现:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector<int>& vec = nums;
int np = 0;
int zp = 0;
while (zp < vec.size() && np < vec.size()) {
while (vec[zp] != 0 ) zp++;
while (vec[np] == 0 || np <= zp) np++;
if (zp >= vec.size() || np >= vec.size()) {
break;
}
std::swap(vec[zp], vec[np]);
zp++; np++;
}
}
};