簡體   English   中英

我怎樣才能讓我的循環更快它花費的時間太長

[英]How can i make my loop faster its taking way too long

我試圖在左旋轉后獲取最大元素的索引。 想法是基於旋轉數組旋轉數組a。 所以旋轉數組是循環的,每個迭代數組 a 都旋轉了很多次作為元素旋轉的值。假設它的 2 則旋轉數組 'a' 2 次。 同時找到旋轉數組的最大元素的索引並保持存儲。 但是代碼執行時間太長,一段時間后測試超時讓我們說這是我的數組

const a = [ 1, 2, 4, 3 ]; 
const rotate = [ 2, 1 ];

預計getLargestItemIndices的 output 將是這樣的數組

[ 0, 1 ]

至於第一次迭代(2次旋轉)最大值(4)在索引0處,第二次迭代最大值在1處

let indices =[];
const getMaxValueIndex = (arr)=>{
    const maxValue = Math.max.apply(Math, arr);
    return arr.indexOf(maxValue);
}

const rotateArray = (a,d)=>{
    while (d) {
      a.push(a.shift());
      d--;
   }
   indices.push(getMaxValueIndex(a));
}

function getLargestItemIndices(a, rotate) {

    for (var index = 0; index < rotate.length; index++) {
        rotateArray(a.slice(), rotate[index]);
    }  
    return indices;
}

我怎樣才能讓我的循環更快它花費的時間太長

TL;DR 通過刪除rotateArray() function

更長的解釋:

我建議把它分成更小的部分。 首先,我會寫一個 function 來獲取輸入數組中最大項的索引。 您可以使用單個 for 循環輕松完成此操作。

現在,一旦您知道最大項目的起始索引。 考慮一下如何在旋轉n位置后快速計算該項目的索引。 rotate數組中的每個數字重復此操作。

暫無
暫無

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

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