-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum_1.java
More file actions
37 lines (29 loc) · 1.03 KB
/
TwoSum_1.java
File metadata and controls
37 lines (29 loc) · 1.03 KB
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
35
36
37
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
*
* 给定 nums = [2, 7, 11, 15], target = 9
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
*/
public class TwoSum_1 {
public static int[] towSum(int[] nums,int targer){
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int tmp = targer - nums[i];
if(map.containsKey(tmp)){
return new int[]{map.get(tmp),i};
}
map.put(nums[i],i);
}
return new int[]{-1,-1};
}
public static void main(String[] args) {
int[] nums = new int[]{2,7,11,15};
int target = 9;
System.out.println(Arrays.toString(towSum(nums, target)));
}
}