454.四数相加
思路:先在AB数组里面求两数的和,放进一个数组里面,再在CD数组中找两个数的和,放进一个数组里面,然后在CD中找有无两个数的和
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> umap;
for (int a : A) {
for (int b : B) {
umap[a + b]++;
}
}
int count = 0; // 统计a+b+c+d = 0 出现的次数
for (int c : C) {
for (int d : D) {
if (umap.find(0 - (c + d)) != umap.end()) {
count += umap[0 - (c + d)];
}
}
}
return count;
}
};
383. 赎金信
取magazine中元素作为hash数组key,频率为val,注入a[]中,再用ransoNote去相减
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int a[26]={0};
if(ransomNote.size()>magazine.size())
{
return false;
}
for(int i:magazine)
{
a[i-'a']++;
}
for(int j:ransomNote)
{
a[j-'a']--;
if(a[j-'a']<0)
{
return false;
}
}
return true;
}
};
还有一种想法是使用COUNT计数法,但还是没有成功
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int count=0;
for(char i:magazine)
{
for(char j:ransomNote)
{
if(i==j)
{
count++;
break;
}
}
}
if(count==ransomNote.size())
{
return true;
}
else
{
return false;
}
}
};