283. 移动零

移动零

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

  • 示例:
    输入: [0,1,0,3,12]
    输出: [1,3,12,0,0]

  • 说明:
    必须在原数组上操作,不能拷贝额外的数组。
    尽量减少操作次数。

  • 分析:

一次遍历数组中的元素,若遍历不为0,则将0和不等于0的元素位置互换,按照升序遍历,既可保证不改变列表中元素顺序,又可保证为0元素排列在不为0元素之后

  • 解法:
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        :input:[0,1,0,3,12]
        :output:[1,3,12,0,0]
        """
    
        zero = 0  # records the position of "0"
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[zero] = nums[zero], nums[i]
                zero += 1
        return nums
原文地址:https://www.cnblogs.com/AimeeCodeWorld/p/10963656.html