【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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章