-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path04_TwoSum.java
More file actions
34 lines (26 loc) · 891 Bytes
/
04_TwoSum.java
File metadata and controls
34 lines (26 loc) · 891 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
// Problem: Two Sum
// Author: Atabul (codeByunique)
import java.util.HashMap;
class TwoSum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = findTwoSum(nums, target);
if (result.length == 2) {
System.out.println("Indices: [" + result[0] + ", " + result[1] + "]");
} else {
System.out.println("No valid pair found.");
}
}
public static int[] findTwoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{}; // no pair found
}
}