Python solution with minimal operations

  • 0
    def moveZeroes(self, nums):
        cur = 0
        for i in xrange(len(nums)):
            if nums[i]:
                nums[cur] = nums[i]
                cur += 1
        for i in xrange(cur, len(nums)):
            nums[i] = 0

    Simple solution with a maximum of n assignments. Use two pointers to shift down non-zero numbers, then fill in the rest with zeros.

  • 1
    def move_zero(nums):
        count = 0
        while 0 in nums:
            count += 1
        return nums   

    How about this solution? I think it is O(n)

  • 0

    It's not O(n) but O(n^2).
    Try/consider move_zero([1] * 10000 + [0] * 10000), for example.

Log in to reply

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