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:
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) {
int size = nums.size();
for (int i = 0; i < size; i++)
{
if (nums.at(i) == 0)
{
nums.push_back(0);
nums.erase(nums.begin()+i);
size--; i--;
}
}
}
};
Implementation 2:
The Idea: We can solve this problem purely using iterators and swaps. The general idea is to swap each zero with the first instance of the next number, given that the zero follows the number. Both iterators begin at 0. We continue to increment the left iterator until we find a zero, do so the same with the number iterator. Given that the number and the zero is found and that the zero follows the number, we can swap the two. This way, we preserve the order of the numbers
Complexity: O(n) time (since both iterators do a single scan through the array at most) and O(1) space
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
zero_i = 0
number_i = 0
size = len(nums)
# idea: swap with the first instance of the next number
while True:
# increment to next zero
while zero_i < size and nums[zero_i] != 0:
zero_i += 1
# implies that we scanned and didnt find zero
if zero_i >= size:
return
# increment to the next number
while number_i < size and nums[number_i] == 0:
number_i += 1
# implies that we scanned and didnt find number
if number_i >= size:
return
# number is in front of the zero, so just move on
# because a swap wont bring the zero forward
if zero_i > number_i:
number_i += 1
continue
# swap
nums[zero_i], nums[number_i] = nums[number_i], nums[zero_i]
Last modified 4yr ago