[英]Find the two numbers that will equal the desired sum
I had a technical interview and one of the questions was to find the two numbers in the array that would equal the desired sum.我进行了一次技术面试,其中一个问题是在数组中找到等于所需总和的两个数字。 For the life of me, I can not find the solution.对于我的生活,我找不到解决方案。
var input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; var dSum = 28; // return would be [12,16]
Use a Set()
, for solving this problem in O(n)
. 使用Set()
解决O(n)
此问题。 The approach is simple : 方法很简单:
Take an empty set. 取一个空集。 And for each element e in input
check: 对于input
检查中的每个元素e:
(a) If the set contains sum - e
. (a)如果集合包含sum - e
。 if yes then print the pair (e, sum -e)
. 如果是,则打印该对(e, sum -e)
。
(b) Insert e into set. (b)将e插入集合。
Try the following: 请尝试以下操作:
let input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; let dSum = 28; let set = new Set(); for(item of input) { let num = dSum - item; if(set.has(num)) { console.log(num + " " + item); break; } set.add(item); }
Please have a look at this simple code because I'm pretty sure this is what you need: 请看一下这个简单的代码,因为我很确定这是您所需要的:
function detectPair(sum, array) { for (i=0; i<array.length; i++) { for (j=0; j<array.length; j++) { if (i == j) continue; else if (array[i] + array[j] === sum) return [array[i], array[j]]; } }; return null; } let sum = 28; let array = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5] console.log(detectPair(sum, array)); //return would be [12,16]
Edit @uom-pgregorio : ' There wasn't any constraints that the same number can't be used. So a 14 + 14 in this case should still be accepted
编辑@ uom-pgregorio :' There wasn't any constraints that the same number can't be used. So a 14 + 14 in this case should still be accepted
There wasn't any constraints that the same number can't be used. So a 14 + 14 in this case should still be accepted
' There wasn't any constraints that the same number can't be used. So a 14 + 14 in this case should still be accepted
'
I'm pretty sure you've mixed something up : The line if (i == j) continue;
我很确定您已经混淆了一些东西 : if (i == j) continue;
is not preventing the situation that 14+14
is correct, it is preventing that if the array just includes a number (like 14)
it uses the same number a several times. 不能防止14+14
是正确的情况,它可以防止如果数组仅包含一个数字(like 14)
则它多次使用相同的数字。
==> `i == j` is checking the indexes not the values
Maybe just try this setup : 也许只需尝试以下设置 :
let sum = 28;
let array = [3, 5, 7, 14, 14] // includes 14 two times
function findSumPair(input, target) { for(let a = 0; a < input.length; a++) { for(let b = a; b < input.length; b++) { if(input[a]+input[b] === target) return [input[a], input[b]]; } } } console.log(findSumPair([3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5], 28));
The inner loop can be started at the current index of the outer loop (rather than 0) because the previous combinations have already been checked. 内循环可以从外循环的当前索引(而不是0)开始,因为已经检查了先前的组合。
var input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; var dSum = 28; // return would be [12,16] let el1 = Math.max(...input) let el2 = Math.max(...input.filter(i => i !== el1)) console.log([el1, el2])
Or 要么
let input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; let dSum = 28; // return would be [12,16] let result for (let i = 0; i < input.length; i++) for (let k = i; k < input.length; k++) if (i !== k && input[i] + input[k] === dSum) result = [input[i], input[k]] console.log(result)
Beside the double nested solutions and solutions with more than one loop, you could use a single loop approach with a hash table for the still missing number and a short circuit if this number is found in the array. 除了双嵌套解决方案和具有多个循环的解决方案之外,您还可以使用带有哈希表的单循环方法来处理仍缺少的数字,如果在数组中找到该数字,则可以短路。
This approach is a fast one, because it uses a for
loop with an object as storage for a fast access, and a variable value
for array[i]
. 这种方法是一种快速的方法,因为它使用带对象的for
循环作为快速访问的存储,并使用array[i]
的变量value
。
Big O is in worst case O(n). 大O在最坏的情况下是O(n)。
function getPair(array, sum) { var i, l, hash = Object.create(null), value; for (i = 0, l = array.length; i < l; i++) { value = array[i]; if (hash[value]) { return [sum - value, value]; } hash[sum - value] = true; } } console.log(getPair([3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5], 28));
I'd say this works, but the algorithm is really bad, O(n^2) I think. 我会说这可行,但是算法确实很糟糕,我认为O(n ^ 2)。
for (i of input) {
for (j of input) {
if (i + j == dSum)
console.log([i, j]);
}
}
function findPair(input, sum) { for(let i = 0; i < input.length; i++) { for(let j = i; j < input.length; j++) { if(input[i] + input[j] == sum) return [input[i], input[j]]; } } return []; } console.log(findPair([3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5], 28));
Try the following: 请尝试以下操作:
for (var i = 0; i < input.length; i++)
for (var j = 0; J < input.length; j++)
if (input[i]+input[j] == dSum)
console.log([input[i], input[j]])
Edit: I thought there was a constraint of i<>j. 编辑:我认为有i <> j的约束。 I removed that constraint 我删除了那个约束
var input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; var dSum = 28; twoSum(input, dSum); function twoSum (arr, target) { let results = []; for (let i=0; i<arr.length; i++) { for (let j=i+1; j<arr.length; j++) { if (arr[j] === target - arr[i]) { results.push([arr[i], arr[j]]) } } } return results; }
@amrender-singh Has the best answer here. @ amrender-singh在这里有最佳答案。
To honour him, here's a snippet using his code to find the first or all sums with a certain value in an Array
为了纪念他,下面是使用他的代码的片段,以查找Array
具有特定值的第一个或所有和
const log = (...strs) => document.querySelector("pre").textContent += `${strs.join(" ")}\\n`; const array = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; log("All possible sums 28 in array:", findSumsInArray(array, 28)); log("First sum 28 in array:", findSumsInArray(array, 28, true)); log("All possible sums 22 in array:", findSumsInArray(array, 22)); log("First sum 22 in array:", findSumsInArray(array, 22, true)); log("All possible sums 12 in array:", findSumsInArray(array, 12)); log("First sum 12 in array:", findSumsInArray(array, 12, true)); log("First sum 28 in array [3, 5, 7, 14, 14]:", findSumsInArray([3, 5, 7, 14, 14], 28, true)); function findSumsInArray(array, sum2Find, firstOnly) { let set = new Set(array); let result = []; const errorStr = `Sum ${sum2Find} not possible in [${array}]`; for (let item of array) { let num = sum2Find - item; if (set.has(num)) { const report = `${num}+${item}`; if (firstOnly) { return report; } result.push(report); set.delete(item); } } return result.length ? `[${result.join(", ")}]` : errorStr; }
<pre></pre>
I'm a bit late in contributing, but no one appears to have posted the obligatory JavaScript one-liner. 我的贡献有点晚了,但是似乎没有人发布强制性的JavaScript一线代码。
let input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5];
let dSum = 28;
let Result = [];
input.forEach( i=>{ input.forEach( j=>{ i+j==dSum && Result.push([i,j]); }); });
The Result
array will contain the solutions, of which there are two in this case: Result
数组将包含解决方案,在这种情况下,其中有两个:
[[12, 16], [16, 12]]
Generalising this to a function where values representing input
and dSum
are user-defined parameters: 将其概括为一个函数,其中代表input
和dSum
值是用户定义的参数:
pairsFromArrayWithSum = (total, Numbers)
=> Numbers.forEach(a => {
Numbers.forEach(b => {
a + b == total && Result.push([a,b]);
}); });
Then, given: 然后,给出:
Result = [];
pairsFromArrayWithSum(50, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]);
the Result
array will contain: Result
数组将包含:
[ [ 3, 47 ],
[ 7, 43 ],
[ 13, 37 ],
[ 19, 31 ],
[ 31, 19 ],
[ 37, 13 ],
[ 43, 7 ],
[ 47, 3 ] ]
let input = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5]; let dSum = 28; let set = new Set(); for(item of input) { let num = dSum - item; if(set.has(num)) { console.log(num + " " + item); break; } set.add(item); }
function detectPair(sum, array) { for (i=0; i<array.length; i++) { for (j=0; j<array.length; j++) { if (i == j) continue; else if (array[i] + array[j] === sum) return [array[i], array[j]]; } }; return null; } let sum = 28; let array = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5] console.log(detectPair(sum, array)); //return would be [12,16]
function detectPair(sum, array) { for (i=0; i<array.length; i++) { for (j=0; j<array.length; j++) { if (i == j) continue; else if (array[i] + array[j] === sum) return [array[i], array[j]]; } }; return null; } let sum = 28; let array = [3, 5, 7, 9, 4, 8, 5, 12, 4, 9, 16, 5] console.log(detectPair(sum, array)); //return would be [12,16]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.