[leetcode]python3 算法攻略-移动零

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

方案一:减一个0,加一个0

def moveZeroes(nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    count = 0
    for i in range(len(nums)):
        if nums[i - count] == 0:
            nums.remove(0)
            nums.append(0)
            count += 1
    return 
方案二:先删去所有的0,最后再补充删去的0
def moveZeroes(nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    count, i = 0, 0
    while i < len(nums):
        if nums[i] == 0:
            nums.remove(0)
            count += 1
        else:
            i += 1
    nums.extend([0] * count)
    return

方案三:不断交换 最早出现的0 和 最迟出现的非零数,j的作用是按顺序记录0的位置

def moveZeroes(nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    j = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[j], nums[i] = nums[i], nums[j]
            j += 1


你可能感兴趣的:(算法练习)