I am just trying to look through an array and find the elements that sum up to the target number. I've gotten this far into the program:
public class App {
public static void main(String[] args) throws Exception {
int[] numbers = {3, 6, 2, 9};
int targNum = 5;
twoSum(numbers, targNum);
}
public static void twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
int sum = 0;
if (nums[i] <= target) {
int[] sumNums = {target - nums[i]};
for (int j = 0; j < sumNums.length; j++) {
sum += sumNums[j];
System.out.println(sum);
}
}
}
}
}
I keep getting console output of:
2
3
I ran a simple array sum in another file and it seemed to work perfectly.
You should use Set to look through the given array only once.
public class App {
public static void main(String[] args) throws Exception {
int[] numbers = { 3, 6, 2, 9 };
int targNum = 5;
twoSum(numbers, targNum);
}
public static void twoSum(int[] nums, int target) {
Set<Integer> unique = new HashSet<>();
for (int a : nums) {
int b = target - a;
if (unique.contains(b)) {
System.out.println(a + " " + b);
return;
}
unique.add(a);
}
System.err.println("not found");
}
}
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