正如@kandelvijaya 所说,如果您想/必须成对比较元素,我不确定您是否能比二次时间做得更好(这在很多情况下都很好)。
这是一个通用的 O(n) 替代方案。两件事:
- 您无需直接比较两个元素,而是提供一个
key 来表示您想要比较的属性。
- 此密钥需要是可散列的(许多标准类型都是如此)。
.
extension Sequence {
typealias Element = Iterator.Element
func uniqued<Key: Hashable>(by key: (Element) -> (Key)) -> [Element] {
var seen = Set<Key>()
return filter {
seen.update(with: key($0)) == nil
}
}
}
用法:
let numbers = [1, 1, 1, 2, 2, 3, 1, 2, 3]
let uniqueByValue = numbers.uniqued { $0 }
let strings = ["a", "b", "aa", "bb", "ccc", "dddd"]
let uniqueByLength = strings.uniqued { $0.characters.count }
在你的情况下,这可能是:
let restaurantes = [R1, R2, R3, R4, R5]
let uniques = restaurants.uniqued {
let roundedLat = ...
let roundedLong = ...
return "\(roundedLat), \(roundedLong)"
}