簡體   English   中英

如何找到更有效地將整數插入Javascript的數組位置?

[英]How do I find the array position in which an integer should be inserted in Javascript more efficiently?

我最近完成了此編程挑戰(在FreeCodeCamp上):

返回將排序后的值(第二個參數)應插入數組(第一個參數)的最低索引。 返回的值應該是一個數字。

例如,getIndexToIns([1,2,3,4],1.5)應該返回1,因為它大於1(索引0)但小於2(索引1)。

同樣,getIndexToIns([20,3,5],19)應該返回2,因為一旦對數組進行排序,它將看起來像[3,5,20],而19小於20(索引2)且大於5(索引1)。

我的代碼可以運行,但效率似乎很低,而且可能不必要地冗長。 我不僅要解決挑戰,而且要成為一名編寫高質量代碼的優秀程序員。 本着這種精神,我希望這里的Javascript專家可以為我提供一些示例,說明如何更有效地解決此問題。

 function getIndexToIns(arr, num) { var diff = 0; var minDiff = 0; var insPos = 0; function sortNumber(a,b) { return a - b; } arr.sort(sortNumber); for(var i = 0; i < arr.length; i++){ diff = num - arr[i]; if(i === 0 || (diff < minDiff && diff >= 0)){ minDiff = diff; if(arr[i] == num){ insPos = i; } else{ insPos = i + 1; } } } return insPos; } 

謝謝你的幫助!

 var arr=[1,2,3,4,5]; function getIndexToIns(num) { var diff = 0; var minDiff = 0; var insPos = 0; arr.sort(sortNumber); var pos=-1; for(var i = 0; i < arr.length; i++){ if(arr[i]>=num){ pos=i; break; } } if(pos>=0){ alert('Index: ' + pos); }else{ alert('Not Found. Perhaps: at ' + arr.length); } } function sortNumber(a,b) { return a - b; } 
 <input type="text" id="num"> <button type="button" onclick=getIndexToIns(document.getElementById('num').value);>Find Pos</button> 

如果我們的輸入數組已排序,則讓要搜索(和插入)的項目為整數甚至對象,此工作最好由二進制搜索算法完成。 給定輸入數組的排序速度,它們比indexOffindIndex 因此,假設輸入數組已經排序,下面的二進制搜索函數將返回搜索到的項目索引,或者如果不存在,則返回負整數,指定否定插入索引。 因此,如果返回-3,則搜索項丟失,應將其插入索引3,以免破壞排序。

PS如果將不存在的項目放置在索引0處,則將返回-0(負零)。

 Array.prototype.sortedFindIndex = function(val, cb = x => x) { // default callback for primitive arrays var deli = this.length-1, // delta index base = 0, // base to add the delta index expectedAt = i => { while (this[i] !== void 0 && cb(this[i]) < val) ++i; return -i}; while (deli > 0 && cb(this[base + deli]) != val) { deli = ~~(deli/2); cb(this[base + deli]) < val && (base += deli); } return cb(this[base + deli]) === val ? base + deli : expectedAt(base + deli); }; var arr = [{a:0,b:"foo"},{a:1,b:"bar"},{a:2,b:"baz"},{a:3,b:"qux"},{a:4,b:"fox"},{a:5,b:"pun"},{a:6,b:"alf"},{a:7,b:"alf"},{a:8,b:"alf"},{a:9,b:"alf"},{a:10,b:"alf"},{a:11,b:"alf"},{a:13,b:"alf"}], brr = [3,6,7,9,13,15,18,21,22,25,29,33,37,42,65], idx = arr.sortedFindIndex(12, o => oa); console.log(idx); idx = brr.sortedFindIndex(27); console.log(idx); 

為了找到最低的索引,應該執行三個步驟:1)在現有數組中添加一個新元素; 2)對新數組中的所有數字進行升序排序; 3)找到要搜索的索引。 如果新數組的所有元素都是數字,則此代碼有效(這足以應付https://www.freecodecamp.com上的挑戰)

function getIndexToIns(arr, num) {
  var newArr = arr;
  newArr.push(num);  //add a new element num to the end of the array

  function compareNumbers(a,b){
    return a - b;
  }

  var sorted = newArr.sort(compareNumbers); //sort the numbers in the array

  for (var i = 0; i < sorted.length; i++)
    {
      if (sorted[i] === num) //index of the element equal to num is the index you are looking for
        {
          return i; 
        }
    }
}
getIndexToIns([2, 20, 10], 19);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM