Given an array say L= [3,4,6,7,2,1] and an Integer Z = 8, find 2 integers X,Y belonging to L such that X + Y = Z
Here is one possible solution -
public static void findIntegersSum(List<Integer> list, int z) {
for(int i = 0 ;i < list.size(); i++) {
for(int j = i+1 ; j< list.size(); j++) {
if(list.get(i) + list.get(j) == z) {
System.out.println(" X = " + list.get(i) + "\t Y=" + list.get(j));
return;
}
}
}
System.out.println(" No match found !!");
}
Question is - Can we optimize the above solution?