Day7 HashTable part2
Leetcode454 4Sum II
[Example]:
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
该题的本质是找元素是否出现在集合里, 左二数组之和的相反数是否会出现在右二数组之和中
思路: 左边两个数组相加得到可能的HashMap的key, 次数由value决定, 该次数是用来被后续的右边两个数组所减
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
HashMap<Integer,Integer> map = new HashMap<>();
int result = 0;
for (int num1: nums1){
for (int num2: nums2){
int sum = num1+num2;
map.put(sum, map.getOrDefault(sum, 0)+1);
}
}
for (int num3: nums3){
for (int num4: nums4){
int res = -(num3 + num4);
if (map.containsKey(res)){
result += map.get(res);
}
}
}
return result;
}
}
Leetcode383 Ransom Note
[Example]:
Input: ransomNote = "a", magazine = "b"
Output: false
和 242.有效的字母异位词 是一个思路, 新建数组/HashMap
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for (int i = 0; i < s.length(); i++){
record[s.charAt(i) - 'a'] += 1;
}
for (int i = 0; i < t.length(); i++){
record[t.charAt(i) - 'a'] -= 1;
}
for (int num: record){
if (num != 0) return false;
}
return true;
}
}