[leetcode] 移动零
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入:
[0,1,0,3,12]
输出:
[1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
思路:双指针,i永远指在第一个0的位置,另个指针去遍历数组,只要数组中有非零元素就去和i的位置交换,并将交换后0位置存储在记录0的位置的数组里,然后i等于记录0的数组中的第一个值,然后把记录0的index数组的第一个值pop掉
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = 0
zeroIndex = []
isFirstZero = True
for index, num in enumerate(nums):
if num == 0 and isFirstZero:
isFirstZero = False
i = index
elif num == 0:
zeroIndex.append(index)
elif num != 0 and isFirstZero == False:
tempNum = nums[index]
nums[index] = 0
nums[i] = tempNum
zeroIndex.append(index)
i = zeroIndex.pop(0)