为清楚起见,这就是我的意思。我想在将生成特定数字的数组(已排序)中寻找两个最小数字。步骤如下:
Example. I need two numbers that when subtracted from the array will give a result of 2.
let givenArray = [1, 4, 8, 10];
The subtraction should go thus: 4 - 1 = 3(doesn't match); //continue
8 - 4 = 1(doesn't match);// continue
8 - 1 = 7(doesn't match); //continue
10 - 8 = 2(match found); //stop and return 8, 10.
注意:此同一数组可能包含6和8或8和10,它们都将产生2,但应该返回6和8。数组的生成方式并不重要。
P.S:我终于在昨天解决了这个问题,但是我不介意其他解决方法。
答案 0 :(得分:2)
此解决方案利用哈希表的优势,并使用单循环方法从数组中获取两个值以平衡两个值。
首先,获取
arrayA
的两个值的绝对增量,并使用它来获取更大数组中的值。然后通过检查所需值是否存在以及总和是否小于先前找到的集合,来减小较大的数组
arrayB
。用于检查的参数是根据
delta
和v
的绝对增量,数组的实际值或通过取delta
和v
的总和构建的为使这一切正常进行,最后一点是,哈希表中包含了实际值
v
,以供以后查找。结果是两个值组成的数组,它们平衡了其他两个值;如果没有找到任何值,则返回
undefined
。
var arrayA = [3, 5],
arrayB = [2, 9, 5, 4],
delta = Math.abs(arrayA[0] - arrayA[1]),
values = {},
result = arrayB.reduce((r, v) => {
function check(w) {
if (!values[w] || r && r[0] + r[1] < v + w) return;
r = [w, v];
}
check(Math.abs(delta - v));
check(delta + v);
values[v] = true;
return r;
}, undefined);
console.log(result);
答案 1 :(得分:0)
我不确定我是否理解正确,但这也许就是您所需要的:
let result = arrayA[1] - arrayA[0];
let i, j;
for (i = arrayB.length - 1; i >= 1; i--) { // Set the first value
for (j = arrayB.length - 1; j >= 1; j--) { // Set the second value
if (i !== j) {
if (
arrayB[i] - arrayB[j] === result // Check substraction
|| arrayB[i] + arrayB[j] === result // Check addition
) return [arrayB[i], arrayB[j]];
}
}
}