Leetcode 数组:283 removezeros 移动零(python)

 

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

示例:

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

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。
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(i)

 

# Cyclic Sort
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[j] , nums[i]= nums[i] , nums[j] j += 1 作者:shan-yin-lu-de-xia-tian-2 链接:https://leetcode-cn.com/problems/move-zeroes/solution/python3-bian-li-ti-huan-by-shan-yin-lu-de-xia-tian/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted @ 2020-04-26 18:15  L1m1t  阅读(197)  评论(0编辑  收藏  举报