scala数组中传递值的上限和下限
Upper and lower of a passed value in a scala Array
我有下面排序的数组 -
scala> Array(10,20,30,40,50)
res15: Array[Int] = Array(10, 20, 30, 40, 50)
如果我传递一个值,如何从中获取下限和上限?
Ex- 如果我通过 11,我应该 return 10 和 20。
如果我过了25,我应该能拿到20和30。
如果我过了10,我应该能拿到10和20。
如果我过了50,我应该能拿到40和50。
如果数组已排序并且我正确理解了问题,我将只搜索比提供的数字大的第一个数字,这是你的上限,下限是索引减去一个
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)
}
EDIT2:将 >
切换为 >=
。要忽略边缘情况,请使用第一种解决方案。
我有下面排序的数组 -
scala> Array(10,20,30,40,50)
res15: Array[Int] = Array(10, 20, 30, 40, 50)
如果我传递一个值,如何从中获取下限和上限?
Ex- 如果我通过 11,我应该 return 10 和 20。
如果我过了25,我应该能拿到20和30。
如果我过了10,我应该能拿到10和20。
如果我过了50,我应该能拿到40和50。
如果数组已排序并且我正确理解了问题,我将只搜索比提供的数字大的第一个数字,这是你的上限,下限是索引减去一个
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)
}
EDIT2:将 >
切换为 >=
。要忽略边缘情况,请使用第一种解决方案。