哈希表理论基础
判断元素在数组里是否出现过:
1. 哈希值比较小,范围也小时,用数组即可。
2. 数值很大时,或者数值不大、但很分散时,用set。
3. 如果key对应value,就用map。
242.有效的字母异位词
思路:
1. 利用字母对应的【acsii码】:把字母的acsii码与a的acsii码的差值【相对数值的思想】转化为哈希表(数组hash[])的索引 => hash[s.charAt(i)-'a']++;
要注意的代码细节:
1. Java String length()方法【注意括号】
class Solution {
public boolean isAnagram(String s, String t) {
int[] hash = new int[26];
for(int i = 0; i<s.length(); i++){
hash[s.charAt(i)-'a']++;
}
for(int i = 0; i<t.length(); i++){
hash[t.charAt(i)-'a']--;
}
for(int i = 0; i<26; i++){
if(hash[i] != 0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
思路:
要注意的代码细节:
1. Set转化为int[]:stream().mapToInt(),转化为一个IntStream,toArray() 转化为数组。
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<>();
for(int i: nums1){
set1.add(i);
}
for(int i: nums2){
if(set1.contains(i)){
resSet.add(i);
}
}
return resSet.stream().mapToInt(x->x).toArray();
}
}
202. 快乐数
思路:
1. 用unordered_set,判断sum是否重复出现。重复了就return false, 否则一直找,直到sum=1。
2. 注意求和过程中,取数值各个位上数字的操作。
要注意的代码细节:
1. n != 1 && !record.contains(n) 作为循环条件,最后return n==1; 代码更简洁。
2. 取数值各个位上数字的操作,循环条件:n>0。
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while(n!= 1 && !record.contains(n)){
record.add(n);
n= getNextNumber(n);
}
return n==1;
}
private int getNextNumber(int n){
int res = 0;
while(n>0){
int temp = n%10;
res += temp * temp;
n = n/10;
}
return res;
}
}
1. 两数之和
思路:
1. 需要知道元素是否遍历过,以及这个元素对应的下标,因此使用 map存放。key存元素,value存下标。
2.遍历数组时,向map查询是否有和目前遍历元素比配的数值。如果有,就找到匹配对;如果没有,就把目前遍历的元素放进map中。
要注意的代码细节:
1. map的存放和判断是同时进行的。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++){
int temp = target - nums[i];
if (map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
}
map.put(nums[i],i);
}
return res;
}
}