1. 程式人生 > >【python3】leetcode 283. Move Zeroes (easy)

【python3】leetcode 283. Move Zeroes (easy)

283. Move Zeroes (easy)

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.

Example:

Input: [0,1,0,3,12]
Output: [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  我的思路

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

Runtime: 48 ms, faster than 94.97% of Python3  

 

2 solution裡看到的一個易懂而神奇的(速度不快

Runtime: 128 ms, faster than 20.26% of Python3 

class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
      
        zeroNum = nums.count(0)
        for i in range(zeroNum):
            nums.remove(0)
            nums.append(0)