+ 1
Checking if any of the 2 numbers adds up to a specific sum?
So I decided at random to write a program that takes an input of several numbers, and checks if any 2 numbers add up to a specific number(This can be anything), and then returns true or false depending on whether or not the program found 2 numbers who's sum is the desired sum. How can I achieve this? Give me some hints. But please, do not give me the answer xD Example: Input: 2, 6, 9, 6 Desired Sum: 12 Output: True //Reason: 6 + 6 = 12 Input: 6, 2, 7, 1 Desired Sum: 4 Output: False I tried explaining as best as I could. Let me know if you don't understand the question.
12 Respostas
+ 5
For each number (n) that is in the array, if you have previously encountered (sum - n), then you have found a pair.
+ 5
VcC That is O(n*log(n)) since you are sorting the list at the beginning.
+ 4
VcC Still O(n*log(n)).
Here is my solution that achieves O(n) complexity by using set:
https://code.sololearn.com/coBOxLw9Kq88/?ref=app
+ 2
Daniel Cooper try this once :
use two for loops... outer one should be on all number in array and inner one should be next number to last number..
if summation is your second input value, you are done...
+ 1
Daniel Cooper , I think I got your problem statement... first input set will be few numbers and second input will be a number... you want to check whether second input can be achieved by any means of summation from set 1 input numbers.... is this correct?
+ 1
Here the code from somebody else:
Use this prototype in any array numbers to find sum up pair..
Array.prototype.ifSumPair = function(sum) {
var len = this.length;
for(var i=0;i<len;i++) {
for(var j=0;j<len;j++) {
if(i===j) continue;
if(sum===(this[i]+this[j])) return true;
}
}
return false;
}
https://code.sololearn.com/Wt12YAFq5uCz/?ref=app
0
Yes. That's exactly correct Ketan Lalcheta
0
Can I have an example Ketan Lalcheta?
0
This can be done with one loop in O(n) time;
l=sorted(l)
a,b=0,len(l)-1
while (l[a]+l[b]!=target and a<b)
if l[a]+l[b]>target: b-=1
else: a+=1
return ((a,b) if a<b else None)
0
Can I see this in pure JS?
Forgot to mention that I want this in JS xD
0
Calviղ my main man always helping me out
lol. Thanks