Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
LeetCode:链接
一共有三种方法。
第一种:创建一个新列表,把不为0的数字加进去,然后再把0加进去。时间复杂度O(n),空间复杂度O(n)。
第二种:将满足的放到前面,不满足的直接覆盖,首先找到第一个0记录位置i,再找到第一个非0记录位置j,将j的值赋值给i的位置,覆盖后i向后移动一个位置,j继续向后查找非0元素,重复赋值的过程直至j走到数组的最后。然后将i后面的数字赋值为0。时间复杂度O(n),空间复杂度O(1)。
第三种:将满足的放到前面,不满足的直接交换到后面。本题就是采用了交换的方式,首先找到第一个0记录位置i,再找到第一个非0记录位置j,将i与j交换,交换后i向后移动一个位置,j继续向后查找非0元素,重复交换的过程直至j走到数组的最后。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
start = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[start], nums[i] = nums[i], nums[start]
start += 1