Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum the elements of the array up to the target number?

Tags:

java

arrays

sum

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.

like image 459
jpenn2472 Avatar asked Jan 28 '26 07:01

jpenn2472


1 Answers

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");

    }

}
like image 85
oleg.cherednik Avatar answered Jan 29 '26 19:01

oleg.cherednik