0
点赞
收藏
分享

微信扫一扫

新书速览|Ubuntu Linux运维从零开始学

徐一村 2024-06-20 阅读 31

题目描述

在这里插入图片描述


最容易想到的解法

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)
举报

相关推荐

0 条评论