283. 移动零 (Swift版本)

题目描述

在这里插入图片描述


最容易想到的解法

从后向前遍历, 发现0就通过交换相邻元素将0移动到最后

class Solution {
    func moveZeroes(_ nums: inout [Int]) {
        for index in (0..<nums.count).reversed() {
            if nums[index] == 0 {
                moveZeroes(&nums, index)
            }
        }
    }

    func moveZeroes(_ nums: inout [Int], _ index: Int) {
        var current = index
        while current < nums.count - 1 {
            nums.swapAt(current, current + 1)
            current += 1
        }
    }
}

最优解 - 双指针

左指针指向当前已经处理好的序列的尾部,右指针指向待处理序列的头部。右指针不断向右移动,每次右指针指向非零数,则将左右指针对应的数交换,同时左指针右移。

class Solution {
    func moveZeroes(_ nums: inout [Int]) {
        let length = nums.count
        var left = 0, right = 0
        while right < length {
            if nums[right] != 0 {
                nums.swapAt(left, right)
                left += 1
            }
            right += 1
        }
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

相关推荐

  1. 【leetcode283移动

    2024-06-13 13:36:03       56 阅读
  2. [leetcode] 283. 移动

    2024-06-13 13:36:03       45 阅读
  3. Leetcode 283. 移动

    2024-06-13 13:36:03       39 阅读
  4. 算法:283. 移动

    2024-06-13 13:36:03       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-13 13:36:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-13 13:36:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-13 13:36:03       82 阅读
  4. Python语言-面向对象

    2024-06-13 13:36:03       91 阅读

热门阅读

  1. python实现跳跃表

    2024-06-13 13:36:03       33 阅读
  2. 代码随想录学习Day 37

    2024-06-13 13:36:03       44 阅读
  3. Android替换默认的按键音

    2024-06-13 13:36:03       34 阅读
  4. 鸿蒙arkts加载组件图片旋转示例

    2024-06-13 13:36:03       33 阅读
  5. 后端Long类型参数前端接受精度丢失解决方案

    2024-06-13 13:36:03       37 阅读
  6. C++中的状态模式

    2024-06-13 13:36:03       29 阅读
  7. C调用C++中的类

    2024-06-13 13:36:03       33 阅读
  8. 【文献阅读】基于高阶矩的波形分类方法

    2024-06-13 13:36:03       36 阅读
  9. Spring MVC的控制器是不是单例模式

    2024-06-13 13:36:03       33 阅读