移动零

作者: 极客匠 | 来源:发表于2019-11-22 00:39 被阅读0次

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

    示例:

    输入: [0,1,0,3,12]
    输出: [1,3,12,0,0]
    说明:

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

    解题思路

    1. 利用python列表方法append、remove来实现
      1. 遍历数组
      2. 当遇到0的数时,在列表最后添加0,删除这个0的数
    class Solution:
        def moveZeroes(self, nums: List[int]) -> None:
            """
            Do not return anything, modify nums in-place instead.
            """
            for i in nums:
                if i == 0:
                    nums.append(0)
                    nums.remove(0)
    
    1. 双指针法

      使用两个下标指针i,j, 遍历数组,当i下标指向的数遇到非0的数时,交换i,j下标的数,并使j+1后移;如果i指向的数为0,则j不变。遍历一遍完成,即能完成移动0的需求

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

    相关文章

      网友评论

          本文标题:移动零

          本文链接:https://www.haomeiwen.com/subject/sxzxwctx.html