题目地址: 283. 移动零
题目陈述:
给定一个数组
nums
,编写一个函数将所有0
移动到数组的末尾,同时保持非零元素的相对顺序。请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0]示例 2:
输入: nums = [0] 输出: [0]
题目解决:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
i,j = 0,0
while j<len(nums):
if nums[j]!=0:
nums[i],nums[j]=nums[j],nums[i]
i+=1
j+=1
return nums
思路与总结 :
首先定义了2个左右指针,右指针的作用是寻找元素0,没有寻找到0,则和左指针互换位置;寻找到了则向右走,左指针也跟着移动;直到右指针走到了尽头,程序返回最终结果nums;