【python3】leetcode 283. Move Zeroes (easy)
283. Move Zeroes (easy)
Given an array
Example:
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:
- You must do this in-place without making a copy of the array.
- 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)