leetcode 283. Move Zeros(移动零) python3 多种思路(移动零 / 移动非零)

本文提供了解决LeetCode中将数组中的所有0移动到末尾同时保持非零元素相对顺序的问题。通过多种方法实现,包括直接交换元素的位置来减少操作次数,达到优化目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。

'''

'''

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.

'''


class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        # Approach #1: 0 个数多的时候效率低下,注意remove()与del 操作的区别,如果用del操作,列表需要倒序遍历。
        #
#         for i in nums:
#             if i == 0:
#                 nums.remove(i)
#                 nums.append(0)

        # Approach #2   删除0,添加0
        # count, length  = 0, len(nums)
        # while count != length:
        #     if nums[count] == 0:
        #         del nums[count]
        #         nums.append(0)
        #         count -= 1
        #         length -= 1
        #     count += 1

        # Approach #3 复制非0,添加零
        # length, new_id = len(nums), 0
        # for i in range(length):
        #     if nums[i] != 0:
        #         nums[new_id] = nums[i]
        #         new_id += 1
        # nums[new_id:] = [0] * (length - new_id)


        # Approach #4: 删除后一次性补零,减少元素位移
        #
        # idxs = [idx for idx , num in enumerate(nums) if num == 0]
        # for i in idxs[::-1]:
        #     nums.pop(i)
        # nums += len(idxs) *[0]




        # Approach #5: 减少交换次数(操作次数就是非零元素的个数)
        # Time:  O(n)
        # Space: O(1)
        #
        j = 0   # 记录非零元素应该换到第几个位置
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[j], nums[i] = nums[i], nums[j]
                j += 1

所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值