考虑排序数组arr
1- 简单案例:
var arr = [3, 6, 12, 18];
indexesAround(6)
//> [1, 1]
indexesAround(7)
//> [1, 2]
2-更复杂的情况:
var arr = [3, 3, 6, 6, 18, 18];
indexesAround(6)
//> [2, 3]
indexesAround(7)
//> [3, 4]
您将如何实现(或伪代码)这样的indexesAround(value)
功能?
--
这是我现在所拥有的,但我认为这可以得到增强:
function indexesAround(val) {
var lower = 0;
var upper = lower;
var el;
for (var i = 0, len = arr.length; i < len; i++) {
el = arr[i];
if (el > val) {break;}
if (arr[lower] < el) {lower = upper = i;}
if (arr[upper] <= el) {upper = i;}
}
return [lower, upper];
}