-
哈希表理论基础:
- 哈希函数:把关键字映射成哈希表中的索引(hashcode),以此插入/查找元素。
- 哈希碰撞:多个关键字的哈希地址相同
- 解决方法:拉链法(哈希表的value以链表的形式存储数据),线性探测法(不改变数据的存储形式,直接将索引++,直到相应的地方为空,再插入元素。)
- 常见用法:用来快速判断一个元素是否出现集合里。
- 常见的三种结构:
- 数组。
- 集合(set)
- map
242、有效的字母异位词
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
//用数组
int len=s.length();
if(len!=t.length()){return false;}
int[] arr=new int[27] ;
int i=0;
while(i<len){
arr[s.charAt(i)-'a']++;
arr[t.charAt(i)-'a']--;
i++;
}
for(int j=0;j<27;j++){
if(arr[j]!=0){
return false;
}
}return true;
349、两个数组的交集
Set<Integer> hss=new HashSet();
Set<Integer> hssNew=new HashSet();
for(int i=0;i<nums1.length;i++){
hss.add(nums1[i]);
}
for(int i=0;i<nums2.length;i++){
if(hss.contains((int)nums2[i])){
hssNew.add(nums2[i]);
}}
int[] res=new int[hssNew.size()];
int i=0;
for(int ff:hssNew){
res[i]=ff;
i++;
}
return res;
- 将结果集合转为数组的方法:
-
return resSet.stream().mapToInt(x -> x).toArray();
202、快乐数
-
题目链接:
202. 快乐数 -
Set<Long> res=new HashSet<>(); long temp=n; while(!res.contains(fun(temp))){ if(fun(temp)==1){return true;} res.add(fun(temp)); temp=fun(temp); } return false; } public long fun(long num){ long sum=0; while(num!=0){ sum+=(num%10)*(num%10); num=num/10;}; return sum; }
1、两数之和
- 题目链接:
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
已经把这道题背下来了hhhhh,感觉用两层循环都不会写了。。。。
-
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<nums.length;i++){ if(hm.containsKey(target-nums[i])){ return new int[]{hm.get(target-nums[i]),i}; }else{ hm.put(nums[i],i);} }return new int[]{0}; } }
-
今天做得不是很顺,感觉要复习一下java基础的collection和map了。。。。