leetcode-283

283. Move Zeroes

Leetcode 283

I solved this problem using C++.
My idea:
set n to the size of the vector nums, and use a for loop to iterate through the vector.
use erase to remove the zero and push_back to add the zero at the end of the vector.
When we remove the zero, we need to decrement i and n by 1, because the size of the vector has changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++)
{
if (nums[i] == 0)
{
nums.erase(nums.begin() + i);
nums.push_back(0);
i--;
n--;
}
}
}
};

e.g.
nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

  1. when i = 0, nums[0] = 0, erase nums[0], push_back 0, i = -1, n = 4
  2. i++, i = 0, nums[0] = 1, i = 0, n = 4
  3. i++, i = 1, nums[1] = 0, erase nums[1], push_back 0, i = 0, n = 3
  4. i++, i = 1, nums[1] = 3, i = 1, n = 3
  5. i++, i = 2, nums[2] = 12, i = 2, n = 3
  6. i++, i = 3, i = 3, n = 3
  7. end of loop

conclusion

Today’s leetcode is easy😏😋…