![](/img/trans.png)
[英]I try to write a function that will return the sum of all array elements that are equal to the number passed in the array. How can I do it?
[英]Write a function that will return the two number array combination with value summed at 5. I can't get all the opportunities
一個職位發布要我寫一個問題的答案,如果我解決了這個問題,我就有資格進入下一輪。
編寫一個函數,該函數將返回總和為 5 的數組組合。重要提示:僅使用一個“for”循環。 示例:var rand_array = [1,3,5,2,4,6]; var target_sum = 5; 輸出 = [1,4], [5], [3,2], [2,3], [4,1];
我試圖在網上找到解決方案並偶然發現了這一點:
https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/因為 StackOverflow 希望你做先自己研究。
但是,當嘗試將其轉換為 JS 時,所發生的一切只是它返回了一種可以工作的情況。 我需要它來返回它工作的每個案例。 然后我做了一些其他的改變,它現在停止工作了。
var ra = [1,3,5,2,4,6];
var target = 5
ra.sort();
lower = 0;
higher = ra.length -1;
var solutions = [];
var result;
while (lower < higher) {
if (ra[lower] + ra[higher] === target){
result = [ra[lower], ra[higher]];
solutions.push(result);
}
else if (ra[lower] + ra[higher] > target){
higher--;
}
else {
lower++;
}
}
return solutions;
}
console.log(solutions);
有人可以為我寫一個例子嗎?
您的代碼不工作,在所有的時刻,因為它並不總是增量lower
或higher
(導致無限循環)。 它還具有比必要更大的復雜性( .sort
具有復雜性O(n log n)
),但說明表明低復雜性很重要。 該數組也沒有按數字排序。 (要按數字排序,請使用.sort((a, b) => a - b)
)
如果您想要一個盡可能復雜度最低的解決方案, O(n)
,在迭代時,創建一個對象。 在每次迭代中,檢查對象是否具有當前數字總和為 5 的鍵(例如,在迭代1
,查看對象上是否存在4
屬性)。 如果找到,請將其添加到解決方案中。 否則,在對象上設置一個新鍵:
const ra = [1, 3, 5, 2, 4, 6]; const target = 5; const solutions = []; const obj = {}; for (const item of ra) { const match = target - item; if (obj[match]) { solutions.push([item, match]); delete obj[match]; } else { obj[item] = true; } } console.log(solutions);
如果可能有重復的數字,則在對象中存儲一個計數,而不僅僅是true
:
const ra = [1, 1, 1, 3, 5, 2, 4, 6, 4, 4]; const target = 5; const solutions = []; const obj = {}; for (const item of ra) { const match = target - item; if (obj[match]) { solutions.push([item, match]); obj[match]--; } else { obj[item] = (obj[item] || 0) + 1; } } console.log(solutions);
我不想寫實際的答案,因為它是一項工作分配,但我會說一個簡單的 2 循環函數是 obvies 解決方案,而不是嘗試認為不從頂部和底部檢查數組,就像編隊一樣循環中的循環。
暗示 :
let i = 0;
let j = 0;
while (i < arr.langth) {
...
if (j < arr.langth) {
j++;
} else {
j = 0;
i++;
}
}
您的代碼根本不起作用。 某些性能有一個可靠的答案,除了它沒有按要求執行任務,即將不同順序的相同數字視為不同或獲取等於目標的值作為解決方案。 這是我對您的問題的解決方案:
const ra = [1,3,5,2,4,6]; const target = 5 function getSumsOfTarget(ra, target){ ra.sort(); lower = 0; higher = ra.length -1; const solutions = []; let result; while (lower < ra.length && higher >= 0) { const sum = ra[lower] + ra[higher]; if (ra[lower] === target) { result = [ra[lower]]; solutions.push(result); break; } if (sum === target){ result = [ra[lower], ra[higher]]; solutions.push(result); lower++; } else if (sum > target){ higher--; } else { lower++; } } return solutions; } console.log(getSumsOfTarget(ra, target));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.