import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class LocalTest {
// Finding sum of two numbers using O(n2)
public static int[] getSum(int arra[], int sum) {
for (int i = 0; i < arra.length; i++) {
for (int j = 0; j < arra.length; j++) {
if (arra[i] + arra[j] == sum) {
return new int[] { arra[i], arra[j] };
}
}
}
return null;
}
//Finding sum of two numbers using O(n)
public static int[] findSum(int arra[], int sum) {
Map<Integer, Integer> arraryMap = new HashMap<Integer, Integer>();
for (int i = 0; i < arra.length; i++) {
int value = arra[i];
if (arraryMap.containsKey(sum - value)) {
return new int[] { arra[arraryMap.get(sum - value)], arra[i] };
}
arraryMap.put(value, i);
}
return null;
}
public static void main(String[] args) {
int arrValues[] = {2,5,7,9,11,3,8 };
System.out.println(Arrays.toString(getSum(arrValues,13)));
System.out.println(Arrays.toString(findSum(arrValues,13)));
}
}
Output
[2, 11]
[2, 11]
Thanks for your valuable comments