less than 1 minute read

283. Move Zeroes

Difficulty: Easy

Related Topics: Array, Two Pointers

Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]

Example 2:

Input: nums = [0] Output: [0]

Code:

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

        if len(nums) == 1:
            return nums
        for i in nums:
            if i == 0:
                nums.remove(i)
                nums.append(i)
        return nums

Feedbacks:

I just simply return nums if nums has only one element. Else, I loop around the list and if element is 0, I remove it and append it to list newly. It passed all the testcases, but I don’t think I used the two pointer algorithm what questions was asking for.