给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
不过脑子做法
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
for i in range(n):
if nums[i] == 0:
nums.remove(nums[i])
nums.append(0)
方法二:
优化双指针
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i]!=0:
if i > j:
nums[j] = nums[i]
nums[i] = 0
j+=1
else:
j+=1