283. Move Zeroes
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 |
|
e.g.
nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
- when i = 0, nums[0] = 0, erase nums[0], push_back 0, i = -1, n = 4
- i++, i = 0, nums[0] = 1, i = 0, n = 4
- i++, i = 1, nums[1] = 0, erase nums[1], push_back 0, i = 0, n = 3
- i++, i = 1, nums[1] = 3, i = 1, n = 3
- i++, i = 2, nums[2] = 12, i = 2, n = 3
- i++, i = 3, i = 3, n = 3
- end of loop
conclusion
Today’s leetcode is easy😏😋…