问题描述
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.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
给定一个数组编号,编写一个函数将所有0移到它的末尾,同时保持非零元素的相对顺序。
注意:
- 必须在不复制数组的情况下就地执行此操作。
- 最小化操作的总数。
输入:
[0,1,0,3,12]
输出:
[1,3,12,0,0]
Python 实现
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
non_zero_len = len(nums)
idx = 0
while idx < non_zero_len:
if nums[idx] == 0:
# Move the zero to the end of list.
nums.pop(idx)
nums.append(0)
non_zero_len -= 1
else:
idx += 1

本文介绍了一个实用的编程技巧,如何在不复制数组的前提下,将数组中所有的零元素移动到数组的末尾,同时保持非零元素的原始顺序。通过Python代码示例,展示了如何高效地实现这一操作,最小化了操作次数。
837

被折叠的 条评论
为什么被折叠?



