-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc_01.java
More file actions
31 lines (26 loc) · 759 Bytes
/
lc_01.java
File metadata and controls
31 lines (26 loc) · 759 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
package leetcode.code;
import java.util.HashMap;
/**
* 两数之和
* 思路:HashMap
*/
public class lc_01 {
public int[] twoSum(int[] nums, int target) {
// 边界检查
if (nums == null || nums.length < 2) {
return new int[]{-1, -1};
}
int[] res = new int[]{-1, -1};
HashMap<Integer, Integer> map = new HashMap<>(); // key 为数组中元素的值,value 为对应的下标
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
res[0] = map.get(target - nums[i]);
res[1] = i;
break;
} else {
map.put(nums[i], i);
}
}
return res;
}
}