【发布时间】:2022-01-15 18:23:09
【问题描述】:
使用此答案中的代码查找数组中最接近的值:https://stackoverflow.com/a/62159057
func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}
如何获取最接近而不是其值匹配的项目的索引?
【问题讨论】:
-
数组排序了吗?这很重要。
-
@vadian 是的,数组是从低到高排序的。
-
那就看看
partitioningIndex(where:)in Swift Algorithms