Given An Array and An Expected Sum, You Are Required To Find The Index of The Two Numbers in The Array Whose Sum Adds Up To The Number.
Given An Array and An Expected Sum, You Are Required To Find The Index of The Two Numbers in The Array Whose Sum Adds Up To The Number.
java
1 import java.util.HashMap;
2 import java.util.Map;
3
4 public class TwoSum {
5 /**
6 * Given an array and an expected sum, you are required to find
7 * the index of the two numbers in the array whose sum adds up
to the number.
8 */
9
10
11 public static void main(String[] args) {
12
13 int[] numbers = new int[] {2,3,7,4,8};
14 int target = 6; // expected: 0 & 3
15
16 int[] answer = test(numbers,target);
17
18 System.out.println(answer[0]+" "+answer[1]);
19
20
21
22 }
23
24
25 public static int[] test(int[] numbers, int target){
26 for(int i=0; i<numbers.length; i++){
27 for(int j=i+1; j<numbers.length; j++){
28 int difference = target‐numbers[i];
29 if (numbers[j]==difference){
30 return new int[] {i,j};
31 }
32 }
33 }
34 throw new IllegalArgumentException("There are no matches"
);
35 }
36
37
38
39
40
41
42
43
44
45
Page 1 of 2
File - C:\Users\daria\OneDrive\Programming\GitHub\Java\JavaPractice\src\TwoSum.java
46
47
48
49
50 public static int[] one(int[] numbers, int target) {
51 // call : int[] result = one(numbers, target);
52 // print: System.out.println(result[0]+" "+result[1]);
53
54 //keeps track of whats already been encountered
55 Map<Integer, Integer> visitedNumbers = new HashMap<>();
56
57 for(int i=0; i<numbers.length; i++){
58
59 int difference = target‐numbers[i];
60
61 if(visitedNumbers.containsKey(difference)){
62 return new int[] {i, visitedNumbers.get(
difference)};
63 }
64 visitedNumbers.put(numbers[i],i);
65 }
66 return new int[] {‐1,‐1};
67 }
68
69 public static int[] two(int[] numbers, int target) {
70 // call : int[] result = two(numbers, target);
71 // print: System.out.println(result[0]+" "+result[1]);
72
73 // this is the brute force method
74
75 for(int i=0; i<numbers.length; i++){
76 for (int j=i+1; i<numbers.length; j++){
77 int difference = target‐numbers[i];
78 if (numbers[j] == difference){
79 return new int[] {i,j};
80 }
81 }
82 }
83
84 throw new IllegalArgumentException("No match found.");
85 }
86
87 }
88
Page 2 of 2