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的例子。
两个选项都返回一个没有重复项的数组。因为第一个选项的复杂性是O(n),我想知道第二个选项是否具有复杂性,如果是,它是什么?