-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoSum.java
More file actions
27 lines (23 loc) · 715 Bytes
/
TwoSum.java
File metadata and controls
27 lines (23 loc) · 715 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
package data_structures.arrays;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int item = 0;item< nums.length; item++){
if(map.containsKey(nums[item])){
return new int[]{item, map.get(nums[item])};
} else {
map.put(target - nums[item], item);
}
}
return null;
}
public static void main(String[] args) {
int[] result = twoSum(new int[]{3, 2, 4}, 6);
assert result != null;
for (int item: result) {
System.out.print(item);
}
}
}