原题
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)
本文介绍了一种在不复制数组的情况下,将所有零元素移至数组末尾同时保持非零元素相对顺序的方法。提供了两种解决方案,一种是通过构造两个列表分别存放零和非零元素再进行拼接,另一种是利用lambda函数对数组进行排序实现。重点讨论了时间复杂度和空间复杂度。
287

被折叠的 条评论
为什么被折叠?



