加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:36:22 所属栏目:百科 来源:网络整理
导读:我正在尝试处理要求的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. 我对这个问题
我正在尝试处理要求的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 ^ 2).

我没有告诉你解决方案,因为它是leetcode.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读