移动零 - 简单
*************
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