哈希表
哈希表基础理论
哈希表主要解决的问题就是给定元素是否出现过
哈希函数
常见的3种哈希结构
有效的字母异位词
题目:LeetCode.242
开一个大小为26的数组,在遍历字符串S时,出现哪个字母就使对应的数组位置的值 + 1,同样在遍历字符串t的时候,对t中出现的字符映射哈希表索引上的数值再
做-1的操作。那么最后检查一下,数组如果有的元素不为零0,则return false
,若全为0,则return true
。
注意:
- 本题中的字符串只含有小写字母。
- 数组的length是属性,不需要加
( )
,而字符串的length是成员方法,需要加( )
。 charAt
的用法for ( : )
的用法
class Solution {
public boolean isAnagram(String s, String t) {
int[] arr = new int[26];
for (int i = 0 ; i < s.length() ; i++){
arr[s.charAt(i) - 'a']++;
}
for (int i = 0 ; i < t.length() ; i++){
arr[t.charAt(i) - 'a']--;
}
for (int cnt : arr){
if (cnt != 0) return false;
}
return true;
}
}
两个数组的交集
题目:LeetCode.349
接口:java.util.Set
函数:
add()
:添加元素contains()
:是否包含某个元素remove()
:删除元素size()
:返回元素数isEmpty()
:是否为空clear()
:清空
stream
:数据源 数据处理 收集结果
import java.util.*;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
//将结果集合转为数组
return resSet.stream().mapToInt(x -> x).toArray();
}
}
快乐数
题目:LeetCode.202
import java.util.*;
class Solution {
public boolean isHappy(int n) {
Set<Integer> res = new HashSet<>();
while (n != 1 && !res.contains(n)){
res.add(n);
n = nextn(n);
}
return n == 1;//false
}
public int nextn(int n){
int cnt = 0;
while (n > 0){
int tmp = n % 10;
cnt += tmp * tmp;
n /= 10;
}
return cnt;
}
}
两数之和
接口:java.util.Map
实现:java.util.HashMap<K, V>
函数:
-
put(key, value)
:添加关键字和其对应的值 -
get(key)
:返回关键字对应的值 -
containsKey(key)
:是否包含关键字 -
remove(key)
:删除关键字 -
size()
:返回元素数 -
isEmpty()
:是否为空 -
clear()
:清空 -
entrySet()
:获取Map中的所有对象的集合 -
Map.Entry<K, V>
:Map中的对象类型-
getKey()
:获取关键字 -
getValue()
:获取值
-
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];//存结果
if(nums == null || nums.length == 0){
return arr;
}
Map<Integer, Integer> res = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int tmp = target - nums[i];
if(res.containsKey(tmp)){
arr[1] = i;
arr[0] = res.get(tmp);
}
res.put(nums[i], i);
}
return arr;
}
}