LeetCode454
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
int ans=0;
unordered_map<int,int> um; //设置查找表
for(int i=0;i<C.size();i++)
{
for(int j=0;j<D.size();j++)
{
um[C[i]+D[j]]++; //将C中元素和D中元素的和放到表中,表中记录次数
}
}
for(int i=0;i<A.size();i++)
{
for(int j=0;j<B.size();j++)
{
int temp=-A[i]-B[j];
if(um.find(temp)!=um.end()) //如果找到temp,说明找到组合相加等于0
{
ans+=um[temp]; //更新组合的个数
}
}
}
return ans;
}
};
LeetCode49
方法1:排序
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for (string& str: strs) {
string key = str;
sort(key.begin(), key.end());
mp[key].emplace_back(str);
}
vector<vector<string>> ans;
for (auto it = mp.begin(); it != mp.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};
方法2:质数相乘
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map <double,vector<string> > m;
double a[26]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
for(string& s : strs)
{
double t = 1;
for(char c : s)
t *= a[c - 'a'];
m[t].push_back(s); //t为单词对应的质数乘积,m[t]则为该单词的异位词构成的vector
}
for(auto& n : m) //n为键和值组成的pair
res.push_back(n.second);
return res;
}
};
LeetCode447
LeetCode149