|
2 | 2 |
|
3 | 3 | import java.util.HashMap;
|
4 | 4 |
|
| 5 | + |
| 6 | +// 两数之和(LeetCode 1):https://leetcode-cn.com/problems/two-sum/ |
| 7 | + |
5 | 8 | public class P0001_Two_Sum {
|
6 | 9 |
|
7 | 10 | 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 | + // 接下来,遍历整个数组 |
9 | 17 | 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 就是这两个值的下标 |
11 | 29 | 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 | + |
14 | 37 | }
|
| 38 | + // 如果遍历完整个数组都找不到和为 target 的两个数,返回 {-1, -1} |
15 | 39 | return new int[]{-1, -1};
|
16 | 40 | }
|
17 | 41 |
|
|
0 commit comments