-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
35 lines (22 loc) · 963 Bytes
/
Copy pathTwoSum.java
File metadata and controls
35 lines (22 loc) · 963 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
34
35
import java.util.HashMap;
public class TwoSum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15, 1, 8, 3, 6};
int target = 9;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i]; // Number needed to reach target
if (map.containsKey(need)) { // Check if we already have that number
int firstIndex = map.get(need);
int secondIndex = i;
int firstNumber = nums[firstIndex];
int secondNumber = nums[secondIndex];
System.out.println("Numbers: " + firstNumber + " + " + secondNumber);
System.out.println("Indexes: " + firstIndex + ", " + secondIndex);
return;
}
map.put(nums[i], i); // Store number and its index
}
System.out.println("No pair found");
}
}