移动零
提示:
- 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之后在末尾补足