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
'DataStructure > Array' 카테고리의 다른 글
Rotate Image (0) | 2018.10.31 |
---|---|
Two Sum (0) | 2018.10.29 |
Plus One (0) | 2018.10.29 |
Intersection of Two Arrays II (0) | 2018.10.29 |
Single Number (0) | 2018.10.29 |