arrays - 将零移动到数组编程练习末尾的性能

标签 arrays swift algorithm performance

我想知道为什么我对这个 LeetCode“移动零点”问题的解决方案比大多数其他提交都慢。有没有更好的方法来解决这个问题以使其更快?

题目如下:

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. You must do this in-place without making a copy of the array.

Example:

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

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

这是我的解决方案:

 func moveZeroes(_ nums: inout [Int]) {
    var index = 0
    for (i,n) in nums.enumerated()
    {
        if n != 0
        {
            nums[index] = n
            index += 1
        }
        
    }
    
    while index < nums.count
    {
        nums[index] = 0
        index += 1
    }
}

LeetCode 给了我这些统计数据:

Runtime: 52 ms, faster than 40.50% of Swift online submissions for Move Zeroes.
Memory Usage: 19.4 MB, less than 13.33% of Swift online submissions for Move Zeroes.

编辑 1:

如果我按如下方式解决问题,它不会移动末尾的零,

enter image description here

编辑 2:

enter image description here

最佳答案

这是适合您的 36 毫秒就地解决方案:

class Solution {
    func moveZeroes(_ nums: inout [Int]) {

        if nums.count < 2 {
            return
        }

        var j = 0

        while j < nums.count, nums[j] != 0 {
            j += 1
        }

        if j < nums.count - 1 {
            for i in j+1..<nums.count {
                if nums[i] != 0 {
                    nums.swapAt(i, j)
                    j += 1
                }
            }
        }
    }
}

36

关于arrays - 将零移动到数组编程练习末尾的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871337/

相关文章:

arrays - Matlab:创建行为相同向量的矩阵。使用 repmat() 或乘以 ones()

ios - Interface Builder 不显示 segues 的 peek 和 pop 选项

algorithm - 如何使空间复杂度为 O(1)

c# - 编程竞赛题目: Counting Polyominos

java - 我怎样才能打印这些整个数组?

c# - 函数中数组参数长度的默认参数值

ios - 更新 PFObject 未按预期工作

algorithm - 数组中任意 k 个元素的数字之和

arrays - 字典中的 Swift 数组导致 NSCFArray

swift - 基本 Swift 类型的完整列表