![](/img/trans.png)
[英]How to improve performance of nested loops in javascript array manipulation?
[英]how to improve performance of nested for loops when comparing values in an array
var twoSum = function(nums, target) {
for(let i = 0; i < nums.length; i++){
for(let j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] === target){
return [nums.indexOf(nums[i]), nums.lastIndexOf(nums[j])]
}
}
}
}
function([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9
這是一個 Javascript 函數,它使用嵌套的 for 循環迭代數字數組,並找到一對,當求和時,它等於目標並返回它們的索引。 由於它有一個嵌套的 for 循環,我相信它具有 O(n^2) 或二次時間復雜度,我想知道是否有更快的方法來做到這一點。 我只是想獲得第一次通過的解決方案,然后對其進行改進。 😁 提前致謝!
創建一個將每個元素映射到其最后一個索引的對象。 然后循環遍歷每個元素,看看target - element
是否在具有不同索引的對象中。
function twoSums(nums, target) { const last_index = {}; nums.forEach((num, i) => last_index[num] = i); for (let i = 0; i < nums.length; i++) { const diff = target - nums[i]; if (diff in last_index && last_index[diff] != i) { return [i, last_index[diff]]; } } } const list = [3,5,3,7,2]; console.log(twoSums(list, 9)); console.log(twoSums(list, 6)); console.log(twoSums(list, 15));
查找一個對象的屬性是 O(1),所以這個算法是 O(n)。
您可以使用嵌套map()
:
var twoSum = (nums, target)=> { // map trough list for first number nums.map( (val1, index1)=> { // map through list again for second number to compare to number returned from first map at each instance nums.map((val2, index2) => { // Ensure that index1 and index2 are not the same before you compare if(index1 != index2 && (val1 + val2 === target)) { alert([index1, index2]); return [index1, index2]; } }); } ); } twoSum([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9
注意:請記住,除非未找到匹配項,否則這不會遍歷所有項目。 一旦找到匹配項,函數就會返回並退出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.