iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 51

[Day 51] Move Zeroes (Easy)

  • 分享至 

  • xImage
  •  

283. Move Zeroes

Solution 1: Two Pointers

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        idxInsert = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                # To avoid the duplicate assign
                if i != idxInsert:
                    nums[idxInsert] = nums[i]
                    idxInsert += 1
                else:
                    idxInsert += 1
        for i in range(idxInsert, len(nums)):
            nums[i] = 0
        return nums

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

Solution 2: SnowBall Move (類似 Two Pointer)

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        snowBallSize = 0 # Consecutive zero
        for i in range(len(nums)):
            if nums[i] == 0:
                snowBallSize += 1
            elif nums[i] != 0 and snowBallSize > 0:
                nums[i - snowBallSize] = nums[i]
                nums[i] = 0
        return nums

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

Solution 3: Swap

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

Reference

https://leetcode.com/problems/move-zeroes/discuss/172432/THE-EASIEST-but-UNUSUAL-snowball-JAVA-solution-BEATS-100-(O(n))-%2B-clear-explanation


上一篇
[Day 50] First Missing Positive (Hard)
下一篇
[Day 52] Linked List Cycle (Easy)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言