Skip to content

Commit cb0918d

Browse files
committed
Create 283-move_zeros.py
1 parent 2dcad12 commit cb0918d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

283-move_zeros.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
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.
3+
4+
Strat: look for non-zero digits in the array. Once you found one, move it to start
5+
of the array. Repeat until you've iterated through the entire array, where
6+
you fill in zeros for the rest of the elements.
7+
8+
Runtime:
9+
Runtime: 32 ms, faster than 93.26% of Python online submissions for Move Zeroes.
10+
Memory Usage: 13.7 MB, less than 5.06% of Python online submissions for Move Zeroes.
11+
"""
12+
class Solution(object):
13+
def moveZeroes(self, nums):
14+
"""
15+
:type nums: List[int]
16+
:rtype: None Do not return anything, modify nums in-place instead.
17+
"""
18+
if len(nums) == 0:
19+
return
20+
21+
finger = 0
22+
23+
#look for non-zero digits in the array
24+
for num in nums:
25+
if num != 0:
26+
nums[finger] = num
27+
finger += 1
28+
29+
#looked through all non-zero digits; replace the rest with 0s
30+
while finger < len(nums):
31+
nums[finger] = 0
32+
finger += 1

0 commit comments

Comments
 (0)