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.
Example:
Input:[0,1,0,3,12]
Output:[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.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
if (nums.size() == 0) {
return;
}
int zero_iter = 0, iter = 0;
while (iter < nums.size()) {
if (nums[iter] == 0) {
break;
}
iter++;
}
if (iter == nums.size()) {
return;
}
zero_iter = iter;
iter = zero_iter + 1;
while (iter < nums.size()) {
if (nums[iter] != 0) {
nums[zero_iter] = nums[iter];
nums[iter] = 0;
zero_iter++;
while (zero_iter < nums.size()) {
if (nums[zero_iter] == 0) {
break;
} else {
zero_iter++;
}
}
}
iter++;
}
return;
}
};
==============
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int size = nums.size();
if (size == 0) {
return;
}
int pos = 0, iter = 0;
while (iter < size) {
if (nums[iter] != 0) {
nums[pos++] = nums[iter];
}
iter++;
}
while (pos != size) {
nums[pos++] = 0;
}
return;
}
};
============
class Solution {
public:
void moveZeroes(vector<int>& nums) {
/*
int zero_idx = 0, cur_idx = 0;
while (zero_idx < nums.size() && nums[zero_idx] != 0) {
zero_idx++;
}
cur_idx = zero_idx;
while (cur_idx < nums.size()) {
if (nums[cur_idx] == 0) {
cur_idx++;
} else {
nums[zero_idx++] = nums[cur_idx];
nums[cur_idx] = 0;
while (zero_idx < nums.size() && nums[zero_idx] != 0) {
zero_idx++;
}
cur_idx = zero_idx;
}
}
*/
int size = nums.size();
if (size == 0) {
return;
}
int pos = 0, iter = 0;
while (iter < size) {
if (nums[iter] != 0) {
nums[pos++] = nums[iter];
}
iter++;
}
while (pos != size) {
nums[pos++] = 0;
}
return;
}
};