LeetCode 283 – Python 3 (Week 3 – 08)

Solution 1

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        zero = 0 #position of 0
        for i in range(len(nums)):
            #if the num is not 0, move the num to the position of last zero
            if nums[i] != 0:
                nums[zero] = nums[i]
                zero += 1
                
        for i in range(zero, len(nums)):
            nums[i] = 0

Time complexity is O(n). Space complexity is O(1).

Solution 2

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nums.sort(key=bool, reverse=True)

Time complexity is O(n log n). Space complexity is O(n).

Solution 3

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        zero = 0
        
        #swap current first 0 and next non-zero elements
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[zero] = 0, nums[i]
                zero += 1

Time complexity is O(n). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started