Skip to content

Commit a7ac230

Browse files
author
Victor An
committed
add comments
1 parent 1cf0fc8 commit a7ac230

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

src/solutions/P0001_Two_Sum.java

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,40 @@
22

33
import java.util.HashMap;
44

5+
6+
// 两数之和(LeetCode 1):https://leetcode-cn.com/problems/two-sum/
7+
58
public class P0001_Two_Sum {
69

710
public int[] twoSum(int[] nums, int target) {
8-
var remainIndexMap = new HashMap<Integer, Integer>();
11+
// 首先构建一个哈希表,用来存放数组的元素值以及索引值
12+
// 其中 key 是数组中的元素值
13+
// value 为数组中元素值的索引
14+
var map = new HashMap<Integer, Integer>();
15+
16+
// 接下来,遍历整个数组
917
for (int i = 0; i < nums.length; i++) {
10-
if (remainIndexMap.containsKey(nums[i])) {
18+
// 目标值为 target,将 target 与 nums[i] 求差
19+
// 获取与 nums[i] 配对的那个数 remain
20+
int remain = target - nums[i];
21+
22+
// 判断哈希表中是否存在那个与 nums[i] 配对的数 remain
23+
if (remainIndexMap.containsKey(remain)) {
24+
// 由于哈希表中所有 key 都是来自于数组中,
25+
// 所以,如果发现哈希表存在那个与 nums[i] 配对的数 remain
26+
// 也就说明数组中存在一个数,可以和 nums[i] 相加为 target
27+
// 此时, remain 这个 key 对应的 value 为这个数在数组中的索引
28+
// 所以,返回 map.get(remain) 和 i 就是这两个值的下标
1129
return new int[]{remainIndexMap.get(nums[i]), i};
12-
}
13-
remainIndexMap.put(target - nums[i], i);
30+
} else {
31+
// 如果发现哈希表中目前不存在那个与 nums[i] 配对的数 anotherNum
32+
// 那么就把此时观察的数 nums[i] 和它的索引存放到哈希表中
33+
// 等待后面的数能和它配对为 target
34+
remainIndexMap.put(nums[i], i);
35+
}
36+
1437
}
38+
// 如果遍历完整个数组都找不到和为 target 的两个数,返回 {-1, -1}
1539
return new int[]{-1, -1};
1640
}
1741

0 commit comments

Comments
 (0)