-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_1.java
33 lines (30 loc) · 917 Bytes
/
prob_1.java
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
import java.util.HashMap;
import java.util.Map;
public class prob_1 {
public static void main(String args[]) {
Solution_1 solution = new Solution_1();
int[] nums = {2,7,11,15};
int target = 9;
int[] indices = solution.twoSum(nums, target);
System.out.println(indices[0] + "," + indices[1]);
return;
}
}
class Solution_1 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> reverseMap = new HashMap<>();
int[] indices = new int[2];
for(int i=0; i<nums.length; i++){
reverseMap.put(target-nums[i], i);
}
for(int i=0; i<nums.length; i++){
Integer index = reverseMap.get(nums[i]);
if(index!=null && index!=i){
indices[0] = i;
indices[1] = index;
break;
}
}
return indices;
}
}