Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
For ex) [0,1,0,3,12]
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
count = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[count] = nums[i]
count += 1
nums[count:] = [0] * (len(nums) - count)
Accepted
75/75 cases passed (59 ms)
Your runtime beats 96.58 % of python3 submissions
Your memory usage beats 16.32 % of python3 submissions (16.5 MB)
Your code is correct and already quite efficient. It moves non-zero elements to the front of the array and fills the remaining positions with zeros. Since you're interested in making it more Pythonic or looking for improvements, you could simplify the loop logic using the enumerate
function:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
count = 0
for i, num in enumerate(nums):
if num != 0:
nums[count], nums[i] = nums[i], nums[count]
count += 1
The enumerate
function makes it easier to iterate over both the index i
and the value num
simultaneously. This approach continues to follow the in-place constraint and maintains linear time complexity.