给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。(第一个我写的,后面自己猜)
class Solution(object):
def moveZeroes1(self, nums: list):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
count_0 = nums.count(0)
length = len(nums) - count_0
i = 0
while i < length:
if nums[i] == 0:
nums.remove(nums[i])
nums.append(0)
continue
i += 1
def moveZeroes2(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if not nums:
return None
length = len(nums)
pre = -1
cur = 0
while cur <length:
if nums[cur]==0:
cur += 1
else:
pre += 1
nums[pre],nums[cur] = nums[cur],nums[pre]
cur+= 1
return nums
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
pos = 0
for i, n in enumerate(nums):
if n != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos += 1
if __name__ == '__main__':
s1 = Solution()
nums = [0, 1, 0, 3, 12]
print(s1.moveZeroes(nums))
print(nums)