给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序
注意事项
1.必须在原数组上操作
2.最小化操作数
样例
给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums = [1, 3, 12, 0, 0].
解答
对于这道题我最开始用的方法很快速。。就是用Python先筛一圈不为零的,然后再筛一圈为零的【个数】,添加在后头。不过报错了。后来想明白报错的原因是因为要求“inplace”操作。不用返回值。
inplace的方法只能是就地转换。我想到的办法是两个指针,第一个指针找“0”,第二个指针找0之后出现的第一个“不为零”的数,然后他们俩调换。
代码如下
class Solution:
# @param {int[]} nums an integer array
# @return nothing, do this in-place
def moveZeroes(self, nums):
# Write your code here
i, j = 0, 0
while i < len(nums):
if nums[i] == 0:
j = i + 1
while j < len(nums):
if nums[j] != 0:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
break
j += 1
if j >= len(nums):
break
i += 1