- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
Latest commit
31 lines (26 loc) · 824 Bytes
/
Copy pathTwoSum.java
File metadata and controls
31 lines (26 loc) · 824 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
/*
int[] nums = {2, 7, 11, 15};
int target = 9;
Output should be the indices [0, 1] because nums[0] + nums[1] = 2 + 7 = 9.
*/
importjava.util.HashMap;
importjava.util.Map;
publicclassTwoSum {
publicstaticint[] twoSum(int[] nums, inttarget) {
Map<Integer,Integer> map = newHashMap<>();
for(inti = 0; i < nums.length;i++){
intvalue = target - nums[i];
if(map.containsKey(value)){
returnnewint[] {map.get(value),i};
}
map.put(nums[i],i);
}
thrownewIllegalArgumentException("No two sum solution");
}
publicstaticvoidmain(String[] args) {
int[] nums = {2, 5, 15, 7};
inttarget = 9;
int [] result = twoSum(nums,target);
System.out.println(result[0] + "," +result[1]);
}
}