Python solution with explaination

  • 0

    Here is my solution for this problem.
    Basically the time complexity is O(n). For each item in the input list, the comparison between the value of index and 0 is conducted. If it is zero, first we shift all the element after it to the end of the list 1 index ahead, then we put 0 to the very end. If it is not zero, shift the index to the next element.

    class Solution(object):
        def moveZeroes(self, nums):
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            idx = 0
            for i in range(len(nums)):
                if nums[idx] == 0:
                    nums[idx:-1] = nums[(idx+1):]
                    nums[-1] = 0
                    idx +=1

Log in to reply

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