四数相加
本题解题步骤:
- 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
- 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。
- 定义int变量count,用来统计 a+b+c+d = 0 出现的次数。
- 再遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
- 最后返回统计值 count 就可以了
C++代码:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> umap; //key:a+b的数值,value:a+b数值出现的次数
// 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中
for (int a : A) {
for (int b : B) {
umap[a + b]++;
}
}
int count = 0; // 统计a+b+c+d = 0 出现的次数
// 再遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。
for (int c : C) {
for (int d : D) {
if (umap.find(0 - (c + d)) != umap.end()) {
count += umap[0 - (c + d)];
}
}
}
return count;
}
};
赎金信
我的解法:使用unordered_set,无法解决magazine
中的每个字符只能在 ransomNote
中使用一次的条件。
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_set word(magazine.begin(),magazine.end());
for(char a : ransomNote){
if(word.find(a) == word.end()){
return false;
}else{
auto it = word.find(a);
word.erase(it);
}
}
return true;
}
};
注意到只有小写字母,可以利用一个26长度的数组作为哈希表:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int word[26]={0};
for(char a : magazine){
word[a-'a']++;
}
for(char a:ransomNote){
if(word[a-'a']==0){
return false;
}else{
word[a-'a']--;
}
}
return true;
}
};