一、题目描述
题目原文:
Given an array
nums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.(输入一个数字列表,我们要把所有的0元后置,并要保持非0元的原顺序)
举例:
For example, given
nums = [0, 1, 0, 3, 12]
, after calling your function,nums
should be[1, 3, 12, 0, 0]
.(输入nums = [0, 1, 0, 3, 12],返回 [1, 3, 12, 0, 0])
二、题目分析
思路:依次判断每个元素,若为0则删除该元素,并在列表末端不上一个0元。
三、Python代码
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(0, len(nums)): if nums[i] == 0: nums.remove(0) nums.append(0)
四、其他
题目链接:https://leetcode.com/problems/move-zeroes/
Runtime: 285 ms
想法不够优化,欢迎大家留言交流~