MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / TwoNumberSum

Class TwoNumberSum

arrays/TwoNumberSum.java:7–33  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5import java.util.Set;
6
7public class TwoNumberSum {
8
9 public static int[] twoNumberSum(int[] array, int targetSum) {
10 Set<Integer> memo = new HashSet<>();
11
12 for (int i = 0; i < array.length; i ++) {
13 int currentNumber = array[i];
14 int valueToCompare = targetSum - currentNumber;
15 if(memo.contains(valueToCompare)) {
16 return new int[] {currentNumber, valueToCompare};
17 } else {
18 memo.add(currentNumber);
19 }
20 }
21
22 return new int[0];
23 }
24
25 public static void main(String[] args) {
26 int[] array = {3, 5, -4, 8, 11, 1, -1, 6};
27 int targetSum = 10;
28
29 int[] result = twoNumberSum(array, targetSum);
30 System.out.println(Arrays.toString(result));
31 }
32
33}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected