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.
移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入:[0,1,0,3,12]输出:[1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
--------------------------------------------------------------------------------------
可以从前往后或是从后往前遍历
若从前往后遍历,找到0之后,要将元素删除,并且指针要减一.然后在数组末端append(0)
若从后往前遍历,则直接删掉元素,append(0)
从前往后
class Solution: @classmethod def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ k = 0 l = len(nums) for i in range(l): if nums[i - k] == 0: del nums[i - k] nums.append(0) k += 1
从后往前
k = 0 l = len(nums) - 1 for i in range(l + 1): if nums[l - k] == 0: del nums[l - k] nums.append(0) k += 1
pythonic
nums.sort(key=lambda x: 1 if x == 0 else 0)
浙公网安备 33010602011771号