Swift, how does my function exceed O (n)?

I am trying to work on a leetcode problem that is asking

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

Find all elements from [1, n] inclusive that are not displayed in this array.

My solution to the problem:

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
}

However, leetcode tells me that my "time limit exceeded" solution

Shouldn't my solution be O (n)? I'm not sure where I made it more than O (n).

+4
source share
1 answer

If I did not miss anything, your algorithm is O (n ^ 2).

, O (n), contains, , O (n ^ 2).

, leetcode.

+7

Source: https://habr.com/ru/post/1693618/


All Articles