移动零:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
算法思路:遇到非零数就进行检查其之前有多少个0,有多少个零就将其向前移动多少个位置,原非零数位置补零。注意!非零数之前没有0则不需要进行移动。
自己实现代码:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)):
if nums[i] != 0:
count = 0
for j in range(0,i): # 检索非零数之前存在多少零
if nums[j] == 0:
count = count + 1
if count == 0: #非零数之前没有零,直接跳出本轮的for循环
continue
else:
nums[i-count] = nums[i] #将此非零数向前移动count个位置
nums[i] = 0 #原非零数位置补零
学习代码:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
for i in nums:
if i == 0:
nums.remove(i) #每次检测到为0的i,将其移除
nums.append(0) #同时在数组尾部加上0
总结:笔者使用了python,并写了一些在python中很愚蠢的代码。为了惩罚自己,我按住了win+R打开了cmd,在指令中输入python得知了我的python版本号为3.9并顺利又畅快地进入到了python的里面,我不敢怠慢,以肃穆的心情重重敲下import this,稳而有力地触按着每一个字母,键盘的啪啪声也在震荡我的算法思路,仿佛在问,你忘掉python的美了吗,我坚定的回答,绝不会!按下了enter键,终于,python之禅出来了。我凝视着python的精华,默念10遍,我完成了对自己的惩罚。
![](https://img-blog.csdnimg.cn/img_convert/0520a2516c50a0c76348de813bf9b6c9.png)