swift - Swift'compactMap'Sequence 方法的时间复杂度
问题描述
Swift 文档指出,compactMap()
用于排序的方法具有时间复杂度,O(n + m)
其中 n 是序列的长度,m 是结果的长度。
但是,在查看标准库中的实现时,我不明白为什么:
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
序列元素只有一个循环,应该是O(n)
.
解决方案
该文档实际上并未说明这是算法的时间复杂度还是内存复杂度。
时间复杂度确实是,O(n)
但是内存复杂度是O(n+m)
,因为原来Sequence
的 sizen
保存在内存中,而新Array
的 sizem
也被创建了。
推荐阅读
- c++ - C ++将一组对象传递给抽象类的成员函数
- oauth-2.0 - 使用“python-o365”库的 OAuth2 身份验证错误
- c# - C# 删除元素并重新排序
- javascript - 如何使用 Javascript 在 vbhtml 中显示带有内容的 div
- python - 试图让脚本运行引用 Ipython,已安装,但不起作用
- python - 熊猫数据框中的颜色列名称
- php - PHP按字母顺序然后按数字对数组键进行排序
- python - python中的小数除法
- javascript - 节点串行端口模块不适用于子进程 fork()
- c# - webClient.DownloadFile() 返回 404