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