原题
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.
解法1
构造两个列表, 一个列表不包含0, 另一个列表包含0, 然后深度复制nums
Time: 2*O(n)
Space: O(1)
代码
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums1 = [n for n in nums if n != 0]
nums2 = [0]*nums.count(0)
nums[:] = nums1 + nums2
解法2
定义lambda函数, 非0的值设为0, 0值设为1, 然后升序排列.
Time: O(n)
Space: O(1)
代码
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort(key = lambda x: 0 if x != 0 else 1)