2019-02-27
阅读量:
830
给定数组编写一个函数将所有 0 移动到数组的末尾
给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
答:我的思路是先删除所有的0,记住一共删除了多少。最后在数组末尾添加同样数量的0.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count_flags = 0
while 0 in nums:
count_flags += 1
nums.pop(nums.index(0))
nums.extend([0 for _ in range(count_flags)])
0.0000
0
1
关注作者
收藏
评论(0)
发表评论
暂无数据
推荐帖子
0条评论
0条评论
0条评论

