Swift 我的函数如何超过 O(n)?

标签 swift algorithm

我正在尝试解决要求的 leetcode 问题

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

我的解决方案是:

func findDisappearedNumbers(_ nums: [Int]) -> [Int] {
    var returnedArray = [Int]()

    if nums.isEmpty == false {
        for i in 1...nums.count {
            if nums.contains(i) == false {
                returnedArray.append(i)
            }
        }
    } else {
        returnedArray = nums
    }
    return returnedArray
}

但是,leetcode 告诉我,我的解决方案是“超出时间限制”

我的解决方案不应该是 O(n) 吗?我不确定我在哪里让它大于 O(n)。

最佳答案

如果我没有遗漏任何东西,你的算法是 O(n^2)。

首先,您遍历数组的每个元素,即 O(n),但是对于每个元素,您调用 contains,它必须再次遍历所有元素,最终得到 O(n) (n^2).

我不告诉你解决方案,因为它是针对 leetcode 的。

关于Swift 我的函数如何超过 O(n)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48781060/

相关文章:

ios - Swift:实现可拖动的 UIImageView 需要哪些方法?

Swift:存储协议(protocol)实例

ios - 将小数格式化为特定小数位数的函数

python - 如何在Python中的类中而不是类之外声明函数

c - 递归算法的时间复杂度

java - 在二维字符数组中查找单词

swift - 如何使用 swift 处理 JSON 中丢失的对象?

ios 10 通知点击什么都不做

python - 大矩阵中的簇数

algorithm - 对于一个包含大量重复元素的数组,有没有什么操作可以提高普通二分查找的性能?