forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
28 lines (23 loc) · 755 Bytes
/
TwoSum.java
File metadata and controls
28 lines (23 loc) · 755 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
package array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] args) {
int[] nums = new int[]{0,2,8,9,13};
int target = 12;
int[] r = twoSum(nums,target);
System.out.print("输出的结果为:"+ Arrays.toString(r));
}
private static int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
int c = target - nums[i];
if(map.containsKey(c)){
return new int[] {map.get(c),i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("no such solutions!");
}
}