考虑排序数组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];
}
答案 0 :(得分:1)
该解决方案涵盖了所有可能性,并且完全符合OP的规范。 Run it on jsfiddle
function indexesAround(target,array) {
var start;
var len = array.length;
for(i = 0; i < len; i++) {
if (array[i] == target && !start) { start = i; }
if (array[i] > target) {
if(i == 0) { return [ 0, 0 ]; } // Target lower than array range
if(!start) { return [ i-1, i ]; } // Target inside array range but not found
return [ start, i-1 ]; // Target found
}
}
if(start) { return [ len-1, len-1 ]; } // Target higher than array range
return [ start, len-1 ]; // Target found and extends until end of array
}
答案 1 :(得分:1)
考虑到数组已排序:
function indexesAround(arr, val) {
if (!~arr.indexOf(val)) return false; // not found
var start = arr.indexOf(val);
var end = (arr.length - 1) - arr.reverse().indexOf(val);
arr.reverse(); // restore original order
return [start, end];
}