LeetCode 283 [Move Zeroes]

原题

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

样例
给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums = [1, 3, 12, 0, 0].

解题思路

  • 第一个方法是记录一个指针指向0,每次swap的时候更新指向零的指针
  • 第二个方法是两个指针,一个指针指向零,一个指针指向非零

完整代码

# method 1
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        pos = 0  # position of "0" starts at
        for i in xrange(len(nums)):
            if nums[i] != 0:
                nums[i], nums[pos] = nums[pos], nums[i]
                pos += 1

# method 2
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if not nums:
            return None
        
        Zero, NonZero = 0, 0
        while NonZero < len(nums):
            if nums[NonZero] == 0:
                NonZero += 1
                continue
            else:
                print nums[Zero], nums[NonZero]
                nums[Zero], nums[NonZero] = nums[NonZero], nums[Zero]

            Zero += 1
            NonZero += 1

你可能感兴趣的:(LeetCode 283 [Move Zeroes])