[LeetCode][Python]283. Move Zeroes

Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

思路:

  1. 移走list中为0的元素,利用collections.Counter得到0的个数,在列表后添加对应个数的0,即是要求的list。(这个方法比较直接,但是估计不符合in-place的要求)
  2. 遍历list每个元素,设置一个坐标元素值为0,如果找到非0值,就和这个坐标元素交换,然后坐标元素值加一。
  3. 设置两个游标,从0开始计数。如果遇到元素不为0,就交换,如此冒泡之后,非0值就会按照顺序已到前列。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        last0 = 0
        for i in xrange(len(nums)):
            if nums[i] != 0:
                nums[i], nums[last0] = nums[last0], nums[i]
                last0 += 1

        return nums

    def moveZeroes2(self, nums):
        nums.sort(cmp=lambda a, b: 0 if b else -1)
        return nums

    def moveZeroes3(self, nums):
        nums.sort(cmp=lambda a, b:-1 if b==0 else 0)
        return nums

    def moveZeroes4(self, nums):
        for i in xrange(nums.count(0)):
            nums.remove(0)
            nums.append(0)
        return nums

    def moveZeroes5(self, nums):
        i = j = 0
        while i < len(nums):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1
            i += 1
        return nums


if __name__ == '__main__':
    sol = Solution()
    s = [0, 1, 0, 3, 12]
    print sol.moveZeroes(s)
    print sol.moveZeroes2(s)
    print sol.moveZeroes3(s)
    print sol.moveZeroes4(s)
    print sol.moveZeroes5(s)

    原文作者:bluescorpio
    原文地址: https://www.jianshu.com/p/d6fd741b01a5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞