这道题一上来的思路是类似冒泡排序,遇到0就沉下去,但这样的操作次数接近于n^2。
因此,我第二个思路是首先遍历一遍数组,记录下0元素的个数和非0元素的个数,然后在第二次遍历中,用i来表示当前遍历到第几个元素,用temp_i来当前非零元素可以放的位置,当非零元素放完之后,剩余的补0,所以一共需要移动元素n次。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
zero_count=0
nonzero_count=0
for num in nums:
if num==0:
zero_count+=1
else:
nonzero_count+=1
temp_i=0
i=0
while temp_i<nonzero_count:
if nums[i]==0:
i+=1
continue
else:
nums[temp_i]=nums[i]
temp_i+=1
i+=1
while temp_i<len(nums):
nums[temp_i]=0
temp_i+=1
return
但是,只超过了72%的提交。从评论中,我发现了一种更快的方法,一共移动元素的次数是非零元素的个数。代码中,x代表当前非0元素能放的位置。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
x = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[x], nums[i] = nums[i], nums[x]
x += 1