283. 移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
提示:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
length = len(nums)
count = 0
for i in range(length):
if nums[i - count] == 0: #每次先查找修改后的第一项,当第一项不是0之后再去查找第二项,同时下次循环将不在查找第一项
nums.insert(length-1, nums.pop(i - count))
print(i, end=' ') #这两行输出为了更加直观的感受代码的运行过程
print(nums)
count += 1
return nums
下面是运行示例,当输入为[0,0,1,0,12,3,4,13,0,2,0]时
输出的结果为
0 [0, 1, 0, 12, 3, 4, 13, 0, 2, 0, 0] #第一次删除0并排到最后一位
1 [1, 0, 12, 3, 4, 13, 0, 2, 0, 0, 0] #第二次查找到0并排到新的最后一位
3 [1, 12, 3, 4, 13, 0, 2, 0, 0, 0, 0]
8 [1, 12, 3, 4, 13, 2, 0, 0, 0, 0, 0]
10 [1, 12, 3, 4, 13, 2, 0, 0, 0, 0, 0]
[1, 12, 3, 4, 13, 2, 0, 0, 0, 0, 0]