2014-11-22 14 views

回答

1

以下函數查找不大於所需值的最大數組元素。換句話說,如果在數組中找到所需的值,它將被返回。否則,將返回一個較小的值,但這將是比目標值小的最大值。這裏有更多的方式來描述它:你將獲得不超過目標的最大價值。

該函數返回一個包含值及其在數組中的索引(位置)的對象。數組中可能有其他元素具有相同的值,但返回的索引是最早元素的索引。

function getBiggestElementNoBiggerThan(arr, x) { // Seeking element x in Array arr. 
 
    if (arr.length == 0) {      // The array must be non-empty, or 
 
     return null;        // else the result is null. 
 
    } 
 
    var best = { value: arr[0], index: 0 },  // Start with the first element. 
 
     n = arr.length; 
 
    for (var i = 1; i < n; ++i) {     // Look at the remaining elements. 
 
     if (arr[i] == x) {      // Have we found the desired value? 
 
      return { value: x, index: i }; 
 
     } else if (arr[i] > x) {     // If not, is it better than our 
 
      best = { value: arr[i], index: i }; // current best? Note that if 
 
     }           // several values are equally 
 
    }            // good, we take the index of the 
 
    return best;         // earliest one. 
 
} 
 

 
function test(arr, x) { 
 
    var result = getBiggestElementNoBiggerThan(arr, x); 
 
    document.write('the biggest element in '+arr.join(', ')+' that is no less than '+ 
 
       x+' is: '+result.value+' at index '+result.index+'<br />'); 
 
} 
 
document.write('tests: <br />'); 
 
test([3, 1, 4, 1, 5, 9], 1); 
 
test([3, 1, 4, 1, 5, 9], 5); 
 
test([3, 1, 4, 1, 5, 9], 8);

相關問題