我有下面的数组与我在一起-
scala> Array(10,20,30,40,50)
res15: Array[Int] = Array(10, 20, 30, 40, 50)
如果传递值,如何从中获得上下限?
例如,如果我通过11,我应该返回10和20。如果我超过25,则应该能够获得20和30。
如果数组已排序并且我正确理解了这个问题,我只会搜索第一个数字,该数字要比所提供的数字大,即您的上限,下限是该索引减去一个]
val arr = Array(10,20,30,40,50)
val numToFind = 11 // or 25
val upperBoundIndex = arr.indexWhere( _ > numToFind )
val lowerBoundIndex = upperBoundIndex - 1
val upperBound = arr(upperBoundIndex)
val lowerBound = arr(lowerBoundIndex)
EDIT1:如果没有提供极端情况,我不知道您要做什么以防万一它溢出或下溢。但是像这样的东西会起作用。
val arr = Array(10,20,30,40,50)
val numToFind = 11 // or 25
val upperBoundIndex = arr.indexWhere( _ > numToFind
if (upperBoundIndex == 0) {
// Upper bound is first so there is no lower bound
} else if (upperBoundIndex == -1) {
// the lower bound is probably your arr.last
} else {
val lowerBoundIndex = upperBoundIndex - 1
val upperBound = arr(upperBoundIndex)
val lowerBound = arr(lowerBoundIndex)
}