移动零
给定一个数组
nums
,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。请注意 ,必须在不复制数组的情况下原地对数组进行操作。
提示:
- 1 <= nums.length <= 104
- 231 <= nums[i] <= 231 - 1
Python代码如下
方法一:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
fast = 0
slow = 0
while fast < len(nums):
if nums[fast] !=0:
nums[fast],nums[slow]=nums[slow],nums[fast]
slow += 1
fast += 1
方法二:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1,-1,-1):
if nums[i] == 0:
nums.pop(i)
nums.append(0)
方法一就是对换,方法二是移除0之后在末尾补足