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问题
我对这个问题的解决方案是: 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 转载:PostgreSQL内核分析 (1)
- c – 在获取地址时隐式实例化函数模板
- postgresql – 适用于Scala的任何中等体面的jdbc包装?
- c# – DryIoc,LightInject体验
- ruby-on-rails – 在Windows上使用Guard和rspec更改文件时,
- c# – Gmail:无法从传输连接中读取数据:net_io_connectio
- firebase – 使用Flutter将对象添加到Cloud Firestore
- Qt15 Update a data from Sqlite database with pushbutton
- ruby-on-rails – 从Ruby中的PDF文件中提取表
- c# – 从XML转换为JSON时更改属性值