Simple and concise Python solution in one pass


  • 0
    H

    The idea is to have two pointers to keep track of the first 0 position and first upcoming non-zero position. Continuously swap them.

    def moveZeroes(self, nums):
    	if len(nums) > 1:
        	j, k = -1, 0
        	for i in xrange(0, len(nums)):
        		if nums[i] == 0 and j == -1:
        			j = i
        		if j != -1 and nums[i] != 0:
        			nums[j] = nums[i]
        			nums[i] = 0
        			j += 1

  • 0
    This post is deleted!

Log in to reply
 

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