Given array a= [1,4,5,9,2].I need to find/print combinations of two values where sum = 6.
My code is as below : (it's O(n^2) and not efficient). Any better solutions -
for(int out=0;out<a.length-1;out++)
{
for(int in=out+1;in<N;in++)
{
if(a[out]+a[in]==6)
{
System.out.println("The 2 numbers are: "+ a[out] +", "+ a[in]);
}
}
}
HashSet.val, check whether 6-val is in the HashSet.I'm not showing code since this looks like homework (if it is, please tag it as such).
Also, for short arrays your O(n^2) solution is almost certainly going to be faster than this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With