MY PYTHON SOLUTION (Using pointers)

  • 0
    class Solution(object):
        def moveZeroes(self, nums):
            You need to keep track of zero_pos to implement in-place swap
            zero_pos = 0
            # need to keep track of zero_pos
            for i in range(len(nums)):
                if nums[i] == 0:
                    zero_pos = i
            # start moving non-zeros to left
            for i in range(zero_pos, len(nums)):
                if nums[i]:
                    nums[i], nums[zero_pos] = nums[zero_pos], nums[i] # swap
                    zero_pos += 1 # update zero position
                # if nums[i] is zero, do nothing.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.