I thought a way to solve the problem which has the following code:
package samueg.algorithm;
public class Main {
public static void main(String[] args) {
int[] numbers = new int[] { -1, 3, 7, 2, 4, 5, -8, 9 };
int sum = 14;
int targetIndex1 = -1, targetIndex2 = -1;
for (int i = 0; i < numbers.length; ++i) {
// for (int j = 0; j < i; ++j) {
// if (numbers[i] + numbers[j] == sum) {
// targetIndex1 = i;
// targetIndex2 = j;
// break;
// }
// }
for (int j = (i + 1); j < numbers.length; ++j) {
if (numbers[i] + numbers[j] == sum) {
targetIndex1 = i;
targetIndex2 = j;
break;
}
}
if (targetIndex1 != -1 && targetIndex2 != -1) {
System.out.println(String.format("%1$d + %2$d = %3$d",
numbers[targetIndex1], numbers[targetIndex2], sum));
return;
}
}
System.out.println("No targets which satisfy the condition are found.");
}
}
The commented code is not necessary because the judgements they do are already done for index i. I want to know whether this algorithm is efficient or not and if it's not can someone show me a better one? Thanks.