leetcode(48)-----283. Move Zeroes

版权声明:本文为博主原创文章,未经允许不得转载。 https://blog.csdn.net/wem603947175/article/details/82501894

283. 移动零
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:

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

思路分析:

  • 1.先找出在数组中是0的这些下标,放入一个sum数组中,并且将0都添加到原数组的末尾。
  • 2.然后按照sum数组,倒序删除原数组中这些0,不删除末尾的。

Python代码实现:

class Solution:
    def moveZeroes(self, nums):
        lenth = len(nums)
        sum = []
        for i in range(0, lenth):
            if nums[i] == 0:
                nums.append(nums[i])
                sum.append(i)
        for i in reversed(sum):
            del nums[i]

猜你喜欢

转载自blog.csdn.net/wem603947175/article/details/82501894