每日一练python20

题目:(移动零)给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12] 输出: [1,3,12,0,0]

程序说明:
1、方法一,就是很简单的对数组进行了一次遍历,使用remove和append函数便轻松解决问题
2、方法二,用了双指针方法,左右指针都从0开始
全部代码:

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)):
            if nums[i]==0:
                nums.remove(nums[i])
                nums.append(0)
        return nums
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        n = len(nums)
        left = right = 0
        while right < n:
            if nums[right] != 0:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
            right += 1

题目来源:力扣(leetcode)

猜你喜欢

转载自blog.csdn.net/qq_52669357/article/details/121479644