Move Zeroes
Problems: Move Zeroes
To solve this problem, we use a sliding window with 2 pointers (We refer all two pointers to a sliding window), one pointer points to the leftmost zero, while the other pointer goes through the array to find non-zero numbers. Once a non-zero number is found, we place it at the leftmost zero and make its original place zero.
For example, we consider italic style and bold style are two pointers, thus we have 0, 1, 0, 3, 12. Then we look ahead and get 0, 1, 0, 3, 12, 1 is a non-zero number, thus re-place it and get 1, 0, 0, 3, 12. We move forward again and get 1, 0, 0, 3, 12 and nothing happens. By next step the array becomes 1, 0, 0, 3, 12 and do replacement. By doing this we can get 1, 3, 0, 0, 12. Repeat these steps we can get the final answer.
Code in Python:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = -1
for r in xrange(len(nums)):
if nums[r] == 0 and l == -1:
l = r
continue
if nums[r] != 0 and l != -1:
nums[l] = nums[r]
nums[r] = 0
l += 1