Leetcode: Move zeros
The task is as follows: Given an integer array
nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
The last note is actually the important part. Without this, it would be easy to just use array splitting in Python and add a zero. This would look similar to this:
This obviously overrides
nums and the change is no longer in place. The next best solution that I found was to delete the items at position I from the list and then add a zero to the end. It is important to note, that the index needs to be decremented by one in case a
0 is found to account for double
0. The number of steps needs to always be increased.
Runtime: 189 ms, faster than 84.86% of Python3 online submissions for Move Zeroes.
Memory Usage: 15.6 MB, less than 17.32% of Python3 online submissions for Move Zeroes.