Python--O(n) solution


  • 3
    Y
    The idea is to move an element in nums p positions left (p being the number of zeros encountered so    far), and finally change the last p elements in nums to 0.
    
    class Solution(object):
            def moveZeroes(self, nums):
                """
                :type nums: List[int]
                :rtype: void Do not return anything, modify nums in-place instead.
                """
                zero_count = 0
                for i in xrange(len(nums)):
                    if nums[i] == 0:
                        zero_count += 1
                        continue
                    nums[i - zero_count] = nums[i]
                for i in xrange(zero_count, 0, -1):
                    nums[-i] = 0

  • 3
    B
    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            N = len(nums)
            i = 0
            while (i < N):
                if nums[i] == 0:
                    nums.pop(i)
                    nums.append(0)
                    N = N-1
                else:
                    i += 1

Log in to reply
 

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