这是一道初级的数组题,考察数组的遍历交换知识
数组的遍历有三种方式:
for i in a:
print(i)
for i in range(0,len(a)):
print('i:',i,'element:',a[i])
for index,element in enumerate(a):
print('Index at',index,'is',element)
前两种比较常用。
解题思路:初始化索引index为0,遍历数组中的元素,若元素非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.
"""
index=0
for num in nums:
if num !=0:
nums[index]=num
index+=1
for i in range(index,len(nums)):
nums[i]=0
这篇博客介绍了如何使用Python处理数组中的零元素,通过遍历数组并交换非零元素的位置,将所有零元素移动到数组末尾。文章详细解析了三种数组遍历方式,并提供了具体的解题代码,实现了在原地修改数组的功能。
510

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



