Leetcode-.283移动零

329 词

本题采用双指针来解决

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:

    def moveZeroes(self, nums: List[int]) -> None:

        """

        Do not return anything, modify nums in-place instead.

        """
        pos=0

        for i in range(len(nums)):

            if nums[i]!=0:

                nums[pos],nums[i]=nums[i],nums[pos]

                pos+=1

本题运用双指针来写:一个指针用来遍历数组,一个用来记录“有效位”索引,如果遍历的时候发现元素不是0,立马就可以跟有效位置索引的数组进行交换,