Python simple two pointer beat 99.71% codes


  • 0

    The real_i is the right position for non-zero element. If "i" is a zero, real_i stay at the original position. All the previous non-zero integer has backed up before real_i.

    class Solution(object):
        def moveZeroes(self, nums):
            real_i = 0
            for i in xrange(len(nums)):
                nums[real_i] = nums[i]
                if nums[i] != 0:
                    real_i += 1
            nums[real_i:] = [0]*(len(nums)-real_i)
    

  • 2
    W

    I believe your last line may create a list as big as the original list. You can easily fix it by looping from real_i to the end and fill it up with 0.


  • 0

    Yeah, your suggestion is absolutely right. I have modify the last line to a loop. Thanks for pointing out. But it should be okay, because the requirement is do it in-place without making a copy of the array! No constant space complexity is required.

    class Solution(object):
        def moveZeroes(self, nums):
            real_i = 0
            for i in xrange(len(nums)):
                nums[real_i] = nums[i]
                if nums[i] != 0:
                    real_i += 1
            for i in xrange(real_i, len(nums)):
                nums[i] = 0
    

Log in to reply
 

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