-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_01_TwoSum.java
More file actions
30 lines (26 loc) · 835 Bytes
/
_01_TwoSum.java
File metadata and controls
30 lines (26 loc) · 835 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
import java.util.HashMap;
import java.util.Map;
public class _01_TwoSum {
static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int remain = target - num;
if (map.containsKey(remain)) {
return new int[] { map.get(remain), i };
}
map.put(num, i);
}
return new int[] {};
}
public static void main(String[] args) {
int[] nums = { 2, 7, 11, 15 };
int target = 9;
int[] res = twoSum(nums, target);
if (res.length == 2) {
System.out.println("Indices: " + res[0] + ", " + res[1]);
} else {
System.out.println("No solution found.");
}
}
}