2024-07-31 15:04:51
,某些文章具有时效性,若有错误或已失效,请在下方留言。集合可以看作是无序数组,不能包含重复元素。如果多次添加相同的元素,它只会在集合中出现一次。
检查数组是否包含一个元素的复杂度为 O(n)
,这意味着 “这取决于数组中有多少个元素”。这是因为 Array.contains()
需要检查从 0 开始的每个元素,因此如果有 50 个元素,则需要进行 50 次检查。检查一个集合是否包含一个项目的复杂度为 O(1)
,这意味着 “无论你有多少个元素,它总是以相同的速度运行”。
基础知识
从数组中创建一个集合
var set1 = Set<Int>([1, 2, 3, 4, 5])
// [4, 3, 5, 1, 2]
print(set1)
集合是无序的,打印的结果可能不相同。
从范围中创建集合
var set2 = Set(1...100)
单独向集合中添加元素
set1.insert(6)
set1.insert(7)
contains()
方法检查集合中是否包含某个元素
if set1.contains(3) {
print("Number 3 is in there!")
}
remove()
从集合中删除元素
set1.remove(3)
数组和集合
数组和集合之间的相互转换
var set1 = Set<Int>([1, 2, 3, 4, 5])
var array1 = Array(set1)
var set2 = Set(array1)
将数组转换为集合再返回是删除所有重复数组的最快方法,而且只需两行代码。
集合的 sorted()
、 map()
和 filter()
方法返回数组。
集合操作
集合的并集,两个集合所有元素合并,可以通过 union
来实现。
let spaceships1 = Set(["Serenity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Executor"])
let union = spaceships1.union(spaceships2)
// ["Voyager", "Serenity", "Executor", "Enterprise", "Nostromo"]
集合的交集,两个集合都存在的元素,可以通过 intersection()
来实现。
let intersection = spaceships1.intersection(spaceships2)
// ["Serenity"]
集合的对称差,两个集合中都不存在的元素。
let difference = spaceships1.symmetricDifference(spaceships2)
// ["Enterprise", "Executor", "Voyager", "Nostromo"]
集合的查询
A.isSubset(of: B)
: 如果集合 A 的所有元素也在集合 B 中,则返回 true。
A.isSuperset(of: B)
: 如果集合 B 的所有元素也在集合 A 中,则返回 true。
A.isDisjoint(with: B)
:如果集合 B 中没有元素也在集合 A 中,则返回 true。
A.isStrictSubset(of: B)
:如果集合 A 的所有元素也在集合 B 中,但 A 和 B 不相等,则返回 true
A.isStrictSuperset(of: B)
:如果集合 B 的所有元素也在集合 A 中,但 A 和 B 不相等,则返回 true
let spaceships1 = Set(["Serenity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Star Destroyer"])
let spaceships3 = Set(["Galactica", "Sulaco", "Minbari"])
let spaceships1and2 = spaceships1.union(spaceships2)
spaceships1.isSubset(of: spaceships1and2) // true
spaceships1.isSubset(of: spaceships1) // true
spaceships1.isSubset(of: spaceships2) // false
spaceships1.isStrictSubset(of: spaceships1and2) // true
spaceships1.isStrictSubset(of: spaceships1) // false
spaceships1and2.isSuperset(of: spaceships2) // true
spaceships1and2.isSuperset(of: spaceships3) // false
spaceships1and2.isStrictSuperset(of: spaceships1) // true
spaceships1.isDisjoint(with: spaceships2) // false
NSCountedSet
元素仍然只能出现一次,但如果您尝试添加多个元素,它就会跟踪计数。
var spaceships = ["Serenity", "Nostromo", "Enterprise"]
spaceships += ["Voyager", "Serenity", "Star Destroyer"]
spaceships += ["Galactica", "Sulaco", "Minbari"]
let countedSet = NSCountedSet(array: spaceships)
print(countedSet.count(for: "Serenity")) // 2
print(countedSet.count(for: "Sulaco")) // 1
可以使用 count(for:)
来获取一个元素在计数集合中出现的次数。
暂无评论内容