-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoNumberSum.java
More file actions
33 lines (25 loc) · 776 Bytes
/
Copy pathTwoNumberSum.java
File metadata and controls
33 lines (25 loc) · 776 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package arrays;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TwoNumberSum {
public static int[] twoNumberSum(int[] array, int targetSum) {
Set<Integer> memo = new HashSet<>();
for (int i = 0; i < array.length; i ++) {
int currentNumber = array[i];
int valueToCompare = targetSum - currentNumber;
if(memo.contains(valueToCompare)) {
return new int[] {currentNumber, valueToCompare};
} else {
memo.add(currentNumber);
}
}
return new int[0];
}
public static void main(String[] args) {
int[] array = {3, 5, -4, 8, 11, 1, -1, 6};
int targetSum = 10;
int[] result = twoNumberSum(array, targetSum);
System.out.println(Arrays.toString(result));
}
}