class Solution:
"""
@param nums: an integer array
@return: nothing
"""
def moveZeroes(self, nums):
# write your code here
#同向型双指针,第一个指针移动,循环赋值,第二个指针移动非0位置,循环给值,最后根据第一个指针,循环赋0
left, right = 0, 0
l = len(nums)
while right < l:
if nums[right] != 0:
nums[left] = nums[right]
left += 1
right += 1
#此时left已经移动到非0的位置,right移动到最右边
while left < l:
nums[left] = 0
left += 1return nums
第二个版本:
class Solution:
"""
@param nums: an integer array
@return: nothing
"""
def moveZeroes(self, nums):
# write your code here
#一个left记录当前非0的位置,right记录走的位置
left, right = 0, 0while right < len(nums):
#right右指针找到非0的个数,left记录下来
if (nums[right] != 0):
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1return nums