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

Swift我的函数如何超过O(n)?,第1张

概述我正在尝试处理要求的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 我正在尝试处理要求的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.

总结

以上是内存溢出为你收集整理的Swift我的函数如何超过O(n)?全部内容,希望文章能够帮你解决Swift我的函数如何超过O(n)?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1005047.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存