-1

考虑排序数组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];
}
4

2 回答 2

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];
}
于 2012-10-10T23:25:33.963 回答
1

该解决方案涵盖了所有可能性,并且完全符合 OP 的规范。在 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
}
于 2012-10-10T23:17:01.143 回答