首页 > 移动平台 > 详细

移动零

时间:2021-02-19 09:54:42      阅读:32      评论:0      收藏:0      [点我收藏+]

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

def moveZeroes1(nums):
    """
    双指针法。注意在数组操作中使用while条件时,下标不要越界。
    """
    length = len(nums)
    i = 0 # 零元素的指针
    j = 0 # 非零元素的指针
    while i < length and j < length:
        while i < length and nums[i] != 0:
            i += 1
        while j < length and nums[j] == 0:
            j += 1
        if j < i: # 如果非零元素的下标小于零元素的下标,不用交换。而且此时二者之间都是非零元素,非零元素的指针可以一步跨到零元素的指针处
            j = i
        if j > i and j < length:
            nums[i], nums[j] = nums[j], nums[i]
            
            
def moveZeroes2(nums):
    """
    遍历,用非零元素覆盖,剩余都填充零。不用考虑下标越界的问题。
    """
    j = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[j] = nums[i]
            j += 1
    for i in range(j, len(nums)):
        nums[i] = 0

移动零

原文:https://www.cnblogs.com/youguang369/p/14414366.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!