Files
flower-rain/docs/石亚玲/syl.md
2025-11-22 21:00:36 +08:00

58 lines
2.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!--
* @Author: buji 1493005357@qq.com
* @Date: 2025-11-22 20:42:32
* @LastEditors: buji 1493005357@qq.com
* @LastEditTime: 2025-11-22 20:50:01
* @FilePath: \flower-rain-2\docs\syl.md
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
## 两数之和
给定一个整数数组`nums`和一个整数目标值`target`。在该数组中找处和为目标值`target`的两个整数,并返回它们的数组下标。
## 题解
```java
public class Solution{
public int[] GetTwoNums(int[] nums , int target){
Map<integer,integer>map = new HashMap<integer,integer>();
for(int i = 0; i < nums.length ; i++){
if(map.containskey(target - nums[i])){
return new int[]{map.get(target - nums[i]),i};
}
map.put(nums[i],i);
}
return new int[0];
}
}
```
## 解释
#### Map
- `Map`是Java中的键值对集合 ;
- 存储的是[key -> value]的映射关系 ;
#### map.containskey()
- 判断`map`中是否存在`target - nums[i]`;
#### map.put()
- 存入map`nums[i]`作为`key``i`作为`value`;
#### map.get()
- 根据传入的`key`,从`HashMap`中获取对应的`value`;
---
## 评价
#### 为什么用 Map 接口而不是直接 HashMap 定义?
- `Map`是Java集合框架中接口定义了“键值对存储”的统一规范`put``get``containskey`等方法。`HashMap``Map`接口的具体实现类。
-`Map`声明变量,是因为此代码只需依赖“键值对存储”的抽象能力,不绑定`HashMap`
- 如果直接用`HashMap`声明,未来切换实现时,需要修改所有需要用到`map`的地方,维护成本极高。
- 哈希表能够实现O(1)快速查找。
#### 时间和空间复杂度比较
- 暴力查找时间O(n²) 空间O(1)
- 哈希查找时间O(n) 空间O(n)
---