刷题日记04
今天开始刷哈希表相关的题
那什么时候需要用到哈希表呢,像是hashmap这样的数据结构,我认为是在集合中查找某个值的时候。
1. 两数之和
哈希表的典型应用
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<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])};
}else{
map.put(nums[i], i);
}
}
return new int[]{0,0};
}
}
202. 快乐数
这道题的隐含条件:如果无限循环应该返回false。这意味着我们需要一个set来缓存所有的sum值,遇到重复就退出循环。
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while( n != 1 && !set.contains(n)){
set.add(n);
int sum = 0;
while(n > 0){
int mod = n % 10;
sum += mod * mod;
n = n / 10;
}
n = sum;
}
return n == 1;
}
}
242. 有效的字母异位词
carl老师用的是数组来解这道题,我这里用了map,其实思路是差不多的,数组可能看上去更简洁一些。
class Solution {
public boolean isAnagram(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
for(char a: s.toCharArray()){
if(map.containsKey(a)){
map.put(a, map.get(a) + 1);
}else{
map.put(a, 1);
}
}
for(char b: t.toCharArray()){
if(map.containsKey(b)){
map.put(b, map.get(b) - 1);
}else{
return false;
}
}
for (Integer value : map.values()) {
if(value != 0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
这道题使用两个set来解决,这里用了一个map和一个set,其实思路是一样的。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> result = new HashSet<>();
for(int n1: nums1){
if(!map.containsKey(n1)){
map.put(n1, 1);
}
}
for(int n2: nums2){
if(map.containsKey(n2)){
result.add(n2);
}
}
return result.stream().mapToInt(x ->x).toArray();
}
}