From 3b9fa3f074b1d39cbfb7000b8a19124a8794f3cb Mon Sep 17 00:00:00 2001 From: mengyi Date: Mon, 10 Jun 2024 17:56:59 -0400 Subject: [PATCH] update running map solution in Java --- .DS_Store | Bin 0 -> 6148 bytes problems/0001.两数之和.md | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..f89600e9deb6f2c531cd456675779b0e188cf6e0 GIT binary patch literal 6148 zcmeHKyG{c^3>-s>lW0;>?l0sIR#EtZ`~X6rGQyC-DdB+wn*x~JCecVr~FDINk;1x$4@br_v zJ?uAm?`5L0Qa}nw0VyB_q`mri^f33h5x+WE_ literal 0 HcmV?d00001 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) {