移动零 - 简单

*************

Python

topic: 283. 移动零 - 力扣(LeetCode)

*************

Give the topic inspection

I am so happy that I am going to 新疆 next week. I rant a car and I will drive there. So I gonna abent python learning for 10 days.

The basic learning is so important, and try an easy topic today. Lanhuage is important, but method stands behind languages. Think different always works. Use double pointers to solve this topic. I am so happy again to go to 新疆, I will see beatiful sence and girls there. Back again.

The red pointer is the fast pointer and the black pointer is the slower pointer. If the fast pointer find the zero eliment, go on and if find the no-zero eliment, swap the red to the black.

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums-in-place instead.
        """
        # left_ptr 用于指向下一个非零元素应该放置的位置
        left_ptr = 0 
        
        # right_ptr 遍历整个数组
        for right_ptr in range(len(nums)):
            # 如果 right_ptr 指向的元素是非零元素
            if nums[right_ptr] != 0:
                # 将该非零元素与 left_ptr 指向的元素进行交换
                # 这样,非零元素被移动到前面(left_ptr的位置),
                # 而原来的元素(可能是0,也可能是它自己,如果left_ptr == right_ptr)
                # 被移动到后面(right_ptr的位置)。
                nums[left_ptr], nums[right_ptr] = nums[right_ptr], nums[left_ptr]
                
                # 移动 left_ptr 指向下一个可以放置非零元素的位置
                left_ptr += 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值