【LeetCode】283. 移動所有的0元素

問題描述

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

給定一個數組編號,編寫一個函數將所有0移到它的末尾,同時保持非零元素的相對順序。

注意:

  1. 必須在不復制數組的情況下就地執行此操作。
  2. 最小化操作的總數。
輸入: 
[0,1,0,3,12]

輸出: 
[1,3,12,0,0]

Python 實現

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        
        non_zero_len = len(nums)
        idx = 0
        while idx < non_zero_len:
            if nums[idx] == 0:
                # Move the zero to the end of list.
                nums.pop(idx)
                nums.append(0)
                non_zero_len -= 1
            else:
                idx += 1

鏈接:https://leetcode.com/problems/move-zeroes/

發佈了46 篇原創文章 · 獲贊 29 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章