1.哈希映射的用法:
哈希映射是用于存储 键——值对(key, value) 的一种实现。
哈希映射的三个常用方法:
put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
remove(key):如果映射中存在这个键,删除这个数值对。
示例:
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // 返回 1
hashMap.get(3); // 返回 -1 (未找到)
hashMap.put(2, 1); // 更新已有的值
hashMap.get(2); // 返回 1
hashMap.remove(2); // 删除键为2的数据
hashMap.get(2); // 返回 -1 (未找到)
哈希函数的简单实例:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值target的那两个整数,并返回他们的数组下标。
方法一:暴力破解(省略)
方法二:哈希映射:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp= target - nums[i];
if (map.containsKey(temp)) { //containsKey():用于检查特定键是否被映射到HashMap中。
return new int[] { map.get(temp), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}