Merge pull request #2581 from MengyiG/mengyiTwoSum

Update problem 1 with running map solution in Java.
This commit is contained in:
程序员Carl
2024-07-04 10:58:12 +08:00
committed by GitHub
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) {