diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..f89600e9 Binary files /dev/null and b/.DS_Store differ diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 580fa3e2..044eac14 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -152,6 +152,24 @@ public int[] twoSum(int[] nums, int target) { return res; } ``` + +```java +//使用哈希表方法2 +public int[] twoSum(int[] nums, int target) { + Map indexMap = new HashMap<>(); + + for(int i = 0; i < nums.length; i++){ + int balance = target - nums[i]; // 记录当前的目标值的余数 + if(indexMap.containsKey(balance)){ // 查找当前的map中是否有满足要求的值 + return new int []{i, indexMap.get(balance)}; // 如果有,返回目标值 + } else{ + indexMap.put(nums[i], i); // 如果没有,把访问过的元素和下标加入map中 + } + } + return null; +} +``` + ```java //使用双指针 public int[] twoSum(int[] nums, int target) {