539. 移动零(两根指针)

539. 移动零

中文English

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

样例

例1:

输入: nums = [0, 1, 0, 3, 12],
输出: [1, 3, 12, 0, 0].

例2:

输入: nums = [0, 0, 0, 3, 1],
输出: [3, 1, 0, 0, 0].

注意事项

1.必须在原数组上操作
2.最小化操作数

 
 
输入测试数据 (每行一个参数)如何理解测试数据?
第一个版本:
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 += 1 
        
        return nums
        

 第二个版本:

class Solution:
    """
    @param nums: an integer array
    @return: nothing
    """
    def moveZeroes(self, nums):
        # write your code here
        #一个left记录当前非0的位置,right记录走的位置
        left, right = 0, 0
        
        while right < len(nums):
            #right右指针找到非0的个数,left记录下来
            if (nums[right] != 0):
                nums[left], nums[right] = nums[right], nums[left]
                left += 1 
            
            right += 1 
        
        return nums
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13194545.html