mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
update running map solution in Java
This commit is contained in:
@ -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) {
|
||||
|
Reference in New Issue
Block a user