0
点赞
收藏
分享

微信扫一扫

Leetcode-数组(8)

移动零

提示:

  • 1 <= nums.length <= 104
  • 231 <= nums[i] <= 231 - 1

Python代码如下
方法一:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        fast = 0
        slow = 0
        while fast < len(nums):
            if nums[fast] !=0:
                nums[fast],nums[slow]=nums[slow],nums[fast]
                slow += 1
            fast += 1

方法二:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)-1,-1,-1):
        	if nums[i] == 0:
        		nums.pop(i)
        		nums.append(0)
        

方法一就是对换,方法二是移除0之后在末尾补足

举报

相关推荐

0 条评论