今日题目:哈希表
242.有效的字母异位词
对于两个单词 a 和 b:
- 统计单词 a 的每个字母的个数
- 对于字母b, 每个字母的个数在哈希表中 -1
- 若最后哈希表中统计的字母个数全为0, 则代表两个字母相同, 否则不相同
class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
for(int i=0; i<t.length(); i++){
char c = t.charAt(i);
map.put(c, map.getOrDefault(c, 0) - 1);
}
for(char c:map.keySet()){
if(map.get(c) != 0) {
return false;
}
}
return true;
}
}
349.两个数组的交集
解题思路:
- 哈希表统计数组 nums1 中的每个元素,hashset 去重
- 哈希表判断nums2中的每个元素是否在哈希表中,若在则符合要求加入结果集,注意对结果集去重
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<nums1.length; i++){
set.add(nums1[i]);
}
List<Integer> list = new ArrayList<>();
for(int i=0; i<nums2.length; i++){
if(set.contains(nums2[i]) && !list.contains(nums2[i])){
list.add(nums2[i]);
}
}
// list -> array
return list.stream().mapToInt(v->v).toArray();
}
}
202.快乐数
解题思路:
- 对于数字n, 判断其是否重复出现过,若重复出现过,则代表不符合要求,返回false
- 若第一次出现,则判断其是否等于1,等于1则符合要求,返回true,不等于1,则将其加入哈希表,并同时更新其为每一位的平方和
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while(!set.contains(n)){
if(n == 1) return true;
set.add(n);
// 求其每一位的平方和
n = getPow(n);
}
return false;
}
// 获取数字每一位的平方和
public int getPow(int n){
int ans = 0;
while(n != 0){
int re = n % 10;
ans += re * re;
n = n / 10;
}
return ans;
}
}
1.两数之和
解题思路:
- 对于每个nums[i], 在哈希表中是否有符合要求的target-nums[i], 若有则返回, 若没有则将其加入哈希表
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(map.containsKey(target-nums[i])){
return new int[]{i, map.get(target-nums[i])};
}
map.put(nums[i], i);
}
return new int[]{};
}
}