[英]Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k
我正在解決這個問題,但似乎無法找到正確的解決方案。 問題是:
“給定一個包含 n 個整數的列表 arr[0..(n-1)],確定其中總和為 k 的不同元素對的數量。如果 integer 多次出現在列表中,則每個副本都被認為是不同;也就是說,如果一對包含至少一個數組索引而另一對不包含,則認為兩對不同,即使它們包含相同的值。
我的方法是構建一個 map,其中包含數組中的每個數字及其出現的次數。 然后我遍歷 map 以找到我的答案。
function numberOfWays(arr, k) {
let output = 0;
let map = {};
// put values and # of occurences into map
for(let i = 0; i < arr.length; i++) {
let key = arr[i];
if(!(key in map)) {
map[key] = 1;
} else {
map[key]++;
}
}
for(let key in map) {
let difference = k-key
if((difference) in map) {
if(k/2 === key) {
output += map[key]*(map[key]-1)/2;
} else {
output += map[key] * map[key] / 2; // divide by 2 so that pairs aren't counted twice
}
}
}
return output;
}
兩個測試用例是:
var arr_1 = [1, 2, 3, 4, 3];
預期結果: [2]
- 我得到[3]
var arr_2 = [1, 5, 3, 3, 3];
預期結果: [4]
——我得到[5.5]
我的計算肯定做錯了,但我似乎無法繞過它。
這是嵌套循環以在數組“arr”中查找總和為“k”的對的一種方法。
function numberOfWays(arr, k) {
let output = 0;
for (i = 0; i < arr.length; i++) {
for (n = i+1; n < arr.length; n++) {
if (arr[i] + arr[n] == k)
output++;
}
}
return output;
}
function numberOfWays(items, k) { // Clone as to not mutate original array const arr = [...items] let count = 0 // Stop comparing when no items left to compare while (arr.length) { for (let i = 0; i < arr.length; i++) { // Compare each item to the first item const sum = arr[0] + arr[i + 1] if (sum === k) { count++ } } // Remove the first item after comparing to the others arr.shift() } return count } console.log(numberOfWays([1, 2, 3, 4, 3], 6)) console.log(numberOfWays([1, 5, 3, 3, 3], 6)) console.log(numberOfWays([1, 1, 1, 1, 1], 2))
您可以計算構建k
的較小和較大值,然后獲取乘積,或者如果只有兩個相同的值正在構建總和,則取 cound 除以 2 的階乘。
function numberOfWays(array, k) { const f = n => +,n || n * f(n - 1); pairs = {}. for (const value of array) { const smaller = Math,min(value; k - value)? pairs[smaller]?:= { one, 2 * smaller === k: min, 0: max; 0 }? pairs[smaller][value === smaller: 'min'; 'max']++; } let count = 0, for (const k in pairs) { const { one, min; max } = pairs[k]; if (one) { if (min > 1) count += f(min) / 2; } else if (min && max) { count += min * max; } } return count. } console,log(numberOfWays([1, 2, 3, 4, 3]; 6)). // 2 console,log(numberOfWays([1, 5, 3, 3, 3]; 6)); // 4
import math
from math import factorial as f
def get_number_of_combination(n,r):
return f(n)//(f(n-r)*f(r))
def numberOfWays(arr, k):
num_count = {}
num_ways = 0
for i in arr:
old_count = num_count.get(i,0)
num_count.update({i: old_count+1})
for i in list(num_count.keys()):
if i == k - i and num_count.get(i,0) > 1:
num_ways += (get_number_of_combination(num_count.get(i,0),2))
num_count.update({i:0})
else:
i_n = num_count.get(i, 0)
ki_n = num_count.get(k-i, 0)
num_ways += i_n * ki_n
num_count.update({i:0,k-i:0})
return num_ways
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.