文章目录
一、 理论知识
1. 哈希表
哈希表中关键码就是数组的索引下标,然后通过下标直接访问数组中的元素
那么哈希表能解决什么问题呢,一般哈希表都是用来快速判断一个元素是否出现集合里。
2. 哈希函数
3. 哈希碰撞
解决哈希冲突的办法:拉链法、线性探测法
4. 常见三种哈希结构
- 数组
int[] object = new int[]; - 集合
无序且 去重
Set<> set = new HashSet<>();
set.add
set.contains
resSet.stream().mapToInt(x -> x).toArray(); set变成数组 - map(映射)
Map<> map = new HashMap<>();
map.containsKey() 判断是否存在key
map.put(nums[i],i) 存放key
map.get(key) 由key取值
5. 核心总结
二、int[ ] 类型
T242. 有效的字母异位词 *
class Solution {
public boolean isAnagram(String s, String t) {
//哈希表:数组形式
//创建一个26长度的数组 遍历字符串,用来计数
int[] record = new int[26];
for (int i = 0;i<s.length();i++){
record[s.charAt(i)-'a']++;
}
for (int j = 0;j<t.length();j++){
record[t.charAt(j)-'a']--;
}
//遍历结果,出现非0,则返回false
for (int k = 0;k<record.length;k++){
if(record[k]!=0){return false;}
}
return true;
}
}
三、Set
T349. 两个数组的交集(Set变成array) **
- 小技巧:
Set集合变成数组int[ ]
res.stream().mapToInt(x -> x).toArray();
class Solution {
//无序且去重采用set格式的hash table
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();//放数组1去重后的结果
Set<Integer> res = new HashSet<>();//存放最终结果
//往1里面放nums1的结果
for (int i:nums1){
set1.add(i);
}
//对2进行处理
for (int i:nums2){
if (set1.contains(i)){
res.add(i);
}
}
//把set转换为数组:stream流
int[] result = res.stream().mapToInt(x -> x).toArray();
return result;
}
}
T202. 快乐数(一个数的各位平方求和)
当在计算过程中,一个结果出现两次,那就会失败,因此用set
class Solution {
//set形式的hashtabke
//当出现1后 则无论循环多少次 结果都是1了 所以只要判断最后一个数即可
public boolean isHappy(int n) {
Set<Integer> sum = new HashSet<>();
while (n!=1 && !sum.contains(n)){ //:若出现了sum则停止循环
sum.add(n);//把n添加进去
//计算数的变换
int res = 0;
while (n>0){
int temp = n % 10;
res += temp*temp;
n = n /10;
}
n = res;
}
return n == 1;
}
}
四、Map (往往需要下标、次数等)
两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
res[0] = i;
res[1] = map.get(target-nums[i]);
}
map.put(nums[i],i);
}
return res;
}
}
T454. 四数相加Ⅱ
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer,Integer> map = new HashMap<>();//值:次数
int res = 0;
int temp = 0;
for(int i:nums1){
for(int j:nums2){
temp = i + j;
if(map.containsKey(temp)){
map.put(temp,map.get(temp)+1);
}else{
map.put(temp,1);
}
}
}
for(int i:nums3){
for(int j:nums4){
temp = i + j;
if(map.containsKey(0-temp)){
res += map.get(0-temp);
}
}
}
return res;
}
}