为了清楚起见,这就是我的意思。我想在将生成特定数字的数组(已排序)中寻找两个最少的数字。步骤如下:
- 遍历数组,每次都设置一个当前值给其他
数会被扣除。- 继续这样做,直到找到与问题匹配的数字并将其返回。
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:我昨天终于解决了它,但我不介意关于如何解决它的其他想法。
最佳答案
此解决方案利用哈希表并使用单循环方法从数组中获取两个值以平衡两个值。
First, take the absolute delta of the two values of
arrayA
and take this for getting the values out of the greater array.Then reduce the greater array
arrayB
by checking if the needed value exist and if the sum is smaller then a previously found set.The argument for checking is build out of the absolute delta of
delta
andv
, the actual value of the array or by taking the sum ofdelta
andv
.The last point, and to make this all working, the actual value
v
is included into the hash table, for a later look up.The result is either an array of two values, which balance the other two values or
undefined
, if no values are found.
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);
关于javascript - 数组中的差/和以检查生成的导致另一个数组的两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55871604/