forked from ghostmkg/dsa-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumArray.java
More file actions
28 lines (24 loc) · 797 Bytes
/
TwoSumArray.java
File metadata and controls
28 lines (24 loc) · 797 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
import java.util.HashMap;
public class TwoSumArray {
public int[] twoSum(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 solution
}
public static void main(String[] args) {
TwoSumArray obj = new TwoSumArray();
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = obj.twoSum(nums, target);
System.out.print("Indices: ");
for (int i : result) {
System.out.print(i + " ");
}
}
}