update running map solution in Java

This commit is contained in:
mengyi
2024-06-10 17:56:59 -04:00
parent bafc930a8a
commit 3b9fa3f074
2 changed files with 18 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

View File

@ -152,6 +152,24 @@ public int[] twoSum(int[] nums, int target) {
return res;
}
```
```java
//使用哈希表方法2
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> 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) {