力扣283 移动0

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(nums.count(0)):
            nums.remove(0)
            nums.append(0)
        

数一数有几个0就给它抠了然后末尾补上。思路很好,就是有点慢。

remove的时间复杂度是O(n)

下面这个同理,稍快一些

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        count = nums.count(0)
        if count == 0 or count == len(nums):
            return 
        nums[:] = [num for num in nums if num!=0] + [0]*count

标准答案是用快慢指针,快指针去探路,遇到不是零的就和慢指针交换位置,交换完慢指针加一。

把非0数存下来,把左边的0全扔到右边去,比较抽象

这么理解,一个指针(快),每遇到一个非零数,都和它左侧最远的那个0交换位置,想象有两个数组。

下面是Java代码

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums.length == 1) {
            return;
        }
        int left = 0;
        int right = 0;
        //右快左慢
        while (right < nums.length) {
            if (nums[right] != 0) {
                int temp = nums[left]; //左右交换
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
            }
            right++;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值