码迷,mamicode.com
首页 > 其他好文 > 详细

283. Move Zeroes

时间:2018-06-09 19:01:02      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:次数   elements   元素   color   this   not   int   说明   col   

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

标签:次数   elements   元素   color   this   not   int   说明   col   

原文地址:https://www.cnblogs.com/jeroen/p/9160312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!