哈希表 相当于把一个数组的元素值当作索引的数据结构 表中的值可以用来处理和记录该索引的个数等。 常用于判断元素是否存在与一个集合中。
有如下三种数据结构。
- 数组
- set (集合)
- map(映射)
242.有效的字母异位词 利用哈希数组记录字符串中一个字符的数量,用26个索引记录
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()){//字符串长度不同则元素个数一定不同
return false;
}
int[] a=new int[26];
for(int i=0;i<s.length();i++){
a[s.charAt(i)-'a']++;//将索引为字符与a的ascii之间的差值的每次加1c 表示s中存在一个该字符
a[t.charAt(i)-'a']--;//减1表示t中存在一个该字符
}
for(int j=0;j<26;j++){//当值为0表示两字符串中该字符数量相同
if(a[j]!=0){
return false;
}
}
return true;
}
}
349. 两个数组的交集 在两个集合中用较小的集合中元素判断其是否存在于另一个集合,存在则元素是其共同元素。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();//初始化一个hash集合
Set<Integer> set2 = new HashSet<Integer>();
for (int num : nums1) {//将nums1添加到集合中
set1.add(num);
}
for (int num : nums2) {
set2.add(num);
}
return getIntersection(set1, set2);
}
public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
if (set1.size() > set2.size()) {//找到较小的集合可以减少遍历次数
return getIntersection(set2, set1);
}
Set<Integer> intersectionSet = new HashSet<Integer>();
for (int num : set1) {//在set1中遍历
if (set2.contains(num)) {//num也在set2中则添加到新集合中
intersectionSet.add(num);
}
}
int[] intersection = new int[intersectionSet.size()];
int index = 0;
for (int num : intersectionSet) {//将set的索引输出为数组
intersection[index++] = num;
}
return intersection;
}
}
202. 快乐数 将数字计算每个位数上的数字的平方和进行循环直到这个数变为 1,也可能始终变不到 1。如果这个过程结果是1,那么这个数就是快乐数。用hash集合记录每次的平方和
class Solution {
public boolean isHappy(int n) {
Set<Integer> result=new HashSet<>();
while(n!=1&&!result.contains(n)){
result.add(n);
n=getsum(n);
}
return n==1;
}
public int getsum(int n){
int sum=0;int a;
while(n>0){
a=n%10;
sum+=a*a;
n=n/10;
}
return sum;//神来之笔
}
}
1. 两数之和 用hashmap记录每个元素,将该元素与target之间的差值与hashmap进行比较,如果存在则成立
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hash.containsKey(target - nums[i])) {
return new int[] { hash.get(target - nums[i]), i };
}
hash.put(nums[i], i);
}
return new int[0];
}
}