class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int,int> hash;
int count=0;
for(auto a:nums1){
for(auto b:nums2){
hash[a+b]++;
}
}
for(auto c:nums3){
for(auto d:nums4){
if(hash.find(0-(c+d))!=hash.end()) count+=hash[0-(c+d)];
}
}
return count;
}
};
2.用char就可以(用真心)
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int> hashm;
for(auto c:magazine) hashm[c]++;
for(auto c:ransomNote){
if (!hashm[c]) return false;
hashm[c]--;
}
return true;
}
};
3.得寸进尺法
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i ++ ) {
if (i && nums[i] == nums[i - 1]) continue;
for (int j = i + 1, k = nums.size() - 1; j < k; j ++ ) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
while (j < k - 1 && nums[i] + nums[j] + nums[k - 1] >= 0) k -- ;
if (nums[i] + nums[j] + nums[k] == 0) {
res.push_back({nums[i], nums[j], nums[k]});
}
}
}
return res;
}
};
4.直接用int会爆,用(long long)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums,int target) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i ++ ) {
if (i && nums[i] == nums[i - 1]) continue;
for (int j = i + 1;j < nums.size(); j ++ ) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
for (int u = j + 1, k = nums.size() - 1; u < k; u ++ ){
if (u > j + 1 && nums[u] == nums[u - 1]) continue;
while (u < k - 1 && ((long long)nums[i] + nums[j] + nums[u] + nums[k - 1]) >= target) k -- ;
if (((long long)nums[i] + nums[j] + nums[u] + nums[k]) == target) {
res.push_back({nums[i], nums[j],nums[u], nums[k]});
}
}
}
}
return res;
}
};