[283] Move Zeroes
https://leetcode.com/problems/move-zeroes/description/
- algorithms
- Easy (52.82%)
- Source Code: 283.move-zeroes.py
- Total Accepted: 447.3K
- Total Submissions: 827.9K
- Testcase Example: '[0,1,0,3,12]'
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.
python
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
lenn = len(nums)
count0 = 0
idx = 0
while idx < lenn:
if nums[idx] == 0:
count0 += 1
else:
if count0 > 0:
nums[idx], nums[idx-count0] = nums[idx-count0], nums[idx]
idx += 1