283. Move Zeroes

Posted jeroen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了283. Move Zeroes相关的知识,希望对你有一定的参考价值。

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.

Example:

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

Note:

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

移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。

--------------------------------------------------------------------------------------

可以从前往后或是从后往前遍历

若从前往后遍历,找到0之后,要将元素删除,并且指针要减一.然后在数组末端append(0)

若从后往前遍历,则直接删掉元素,append(0)

从前往后

class Solution:
    @classmethod
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        k = 0
        l = len(nums)
        for i in range(l):
            if nums[i - k] == 0:
                del nums[i - k]
                nums.append(0)
                k += 1

 

从后往前

        k = 0
        l = len(nums) - 1
        
        for i in range(l + 1):
            if nums[l - k] == 0:
                del nums[l - k]
                nums.append(0)
            k += 1

 

以上是关于283. Move Zeroes的主要内容,如果未能解决你的问题,请参考以下文章

283. Move Zeroes

283. Move Zeroes

283. Move Zeroes

算法:移动零283. Move Zeroes

LeetCode 283. Move Zeroes

283. Move Zeroes