-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution1.java
More file actions
34 lines (26 loc) · 782 Bytes
/
Solution1.java
File metadata and controls
34 lines (26 loc) · 782 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
32
33
34
import java.util.HashMap;
import java.util.Map;
/**
* 借助map的检索特性减少遍历次数
*/
public class Solution1 {
public static void main(String[] args) {
int []nums = {2, 7, 11, 15};
int target = 9;
int[] ints = twoSum(nums, target);
System.out.println(ints[0]+"--"+ints[1]);
}
private static int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> tracer = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if(tracer.containsKey(num)){
int value = tracer.get(num);
return new int[]{value,i};
}else{
tracer.put(target-num,i);
}
}
return new int[]{};
}
}