DataStructure/Array
Move Zeroes
ND Paul Kim
2018. 10. 29. 18:13
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.
My solution:
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
size = len(nums)
index = 0
for i in range(size):
if nums[i] != 0:
val = nums[i]
del nums[i]
nums.insert(index, val)
index +=1
Good solution:
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count=nums.count(0)
nums[:]=[i for i in nums if i != 0]
nums+=[0]*count