Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a list 1, 4, 5,9,2 write a program to find possible combinations of two values where sum = 6

Tags:

java

arrays

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]);
    }
    }
}
like image 471
srock Avatar asked Dec 06 '25 10:12

srock


1 Answers

  1. Place all numbers into a HashSet.
  2. Iterate over the array, and for each item 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.

like image 100
NPE Avatar answered Dec 07 '25 23:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!