从一个集合中初始化一个数组是否很复杂,如果是的话是什么?
Does initializing an array from a set have a complexity and if so what is it?
Swift: 选项 1
var dictionaryWithoutDuplicates = [Int: Int]()
for item in arrayWithDuplicates {
if dictionaryWithoutDuplicates[item] == nil {
dictionaryWithoutDuplicates[item] = 1
}
}
print(dictionaryWithoutDuplicates.keys)
// [1,2,3,4]
选项 2
let arrayWithDuplicates = [1,2,3,3,2,4,1]
let arrayWithoutDuplicates = Array(Set(arrayWithDuplicates))
print(arrayWithoutDuplicates)
// [1,2,3,4]
对于第一个选项,可能有更优雅的方法来实现,但这不是我的意思,我只是想展示一个复杂度为 n 的示例。
两个选项 return 一个没有重复的数组。由于第一个选项的复杂度为 O(n),我想知道第二个选项是否也有复杂度,如果有,它是什么?
您所做的几乎就是 Set
所做的。 Set<T>
几乎就是 [T: Void]
(a.k.a. Dictionary<T, Void>
).
两个例子都有 O(arrayWithDuplicates.count)
时间和 space 复杂度。
Swift: 选项 1
var dictionaryWithoutDuplicates = [Int: Int]()
for item in arrayWithDuplicates {
if dictionaryWithoutDuplicates[item] == nil {
dictionaryWithoutDuplicates[item] = 1
}
}
print(dictionaryWithoutDuplicates.keys)
// [1,2,3,4]
选项 2
let arrayWithDuplicates = [1,2,3,3,2,4,1]
let arrayWithoutDuplicates = Array(Set(arrayWithDuplicates))
print(arrayWithoutDuplicates)
// [1,2,3,4]
对于第一个选项,可能有更优雅的方法来实现,但这不是我的意思,我只是想展示一个复杂度为 n 的示例。 两个选项 return 一个没有重复的数组。由于第一个选项的复杂度为 O(n),我想知道第二个选项是否也有复杂度,如果有,它是什么?
您所做的几乎就是 Set
所做的。 Set<T>
几乎就是 [T: Void]
(a.k.a. Dictionary<T, Void>
).
两个例子都有 O(arrayWithDuplicates.count)
时间和 space 复杂度。