[Leetcode] 283. Move Zeroes

김지원·2022년 3월 11일
0

📄 Description

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]

🔨 My Solution

💻 My Submission

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if 0 not in nums:
            return
        p_zero=nums.index(0)
        p_n_zero=0
        while p_n_zero<len(nums) and p_zero<len(nums):
            p_zero=nums.index(0)
            if nums[p_zero]==0 and nums[p_n_zero]!=0 and p_zero<p_n_zero:
                nums[p_zero],nums[p_n_zero]=nums[p_n_zero],nums[p_zero]
                p_n_zero+=1
            elif nums[p_n_zero]==0:
                p_n_zero+=1
            else:
                p_n_zero+=1

🔎 Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Runtime: 3316 ms
Memory: 15.7 MB

💭 Why did it took so much time..?

💊 Better Solutions

1. using sort method

nums.sort(key=lambda x:x==0)

2. using two pointers with better approach

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        cur = 0
        for i in range(len(nums)):
            if nums[i]:
                nums[cur], nums[i] = nums[i], nums[cur]
                cur += 1

🔎 Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Runtime: 225 ms
Memory: 15.6 MB

References
https://leetcode.com/problems/move-zeroes/

profile
Make your lives Extraordinary!

0개의 댓글