题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/25520fe5534b769ca770c477fd982611.png)
解题思路
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int,int> umap;
for(int a :nums1)
{
for(int b:nums2)
{
umap[a+b]++;
}
}
int count = 0;
for(int a: nums3)
{
for(int b:nums4)
{
if(umap.find(0-(a+b))!=umap.end())
{
count += umap[0-(a+b)];
}
}
}
return count;
}
};
题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/947f7b7da8ea893f5494224b7da7c536.png)
解题思路
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> hasha(26,0);
vector<int> hashb(26,0);
for(auto a:ransomNote)
{
hasha[a-'a']++;
}
for(auto b:magazine)
{
hashb[b-'a']++;
}
for(int i = 0; i<hasha.size();++i)
{
hasha[i] = hasha[i]-hashb[i];
}
for(auto a:hasha)
{
if(a>0)
{
return 0;
}
}
return 1;
}
};
题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b3c52957d0ada17e392d2e5c4cb54c19.png)
解题思路
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>ans;
sort(nums.begin(),nums.end());
for(int i = 0 ;i<=nums.size()-3;++i)
{
if (nums[i] > 0)
{
return ans;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i+1;
int right = nums.size()-1;
while(left<right)
{
if(nums[i]+nums[left]+nums[right]>0)
{
right--;
}
else if(nums[i]+nums[left]+nums[right]<0)
{
left++;
}
else
{
ans.push_back(vector<int>{nums[i],nums[left],nums[right]});
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
return ans;
}
};
题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/535f241e7f0e1613a0d1bfb9cbed9a88.png)
解题思路
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>>ans;
sort(nums.begin(),nums.end());
for(int i = 0; i<nums.size();++i)
{
if(nums[i]>target&& nums[i]>=0)
{
break;
}
if(i>0&& nums[i]==nums[i-1])
{
continue;
}
for(int j = i+1;j<nums.size();++j)
{
if(nums[i]+nums[j]>target&& nums[j]+nums[i]>=0)
{
break;
}
if(j>i+1&&nums[j]==nums[j-1])
{
continue;
}
int left = j+1;
int right = nums.size()-1;
while(left<right)
{
if((long)nums[i]+nums[j]+nums[left]+nums[right]>target)right--;
else if((long)nums[i]+nums[j]+nums[left]+nums[right]<target)left++;
else{
ans.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]});
while(left<right&&nums[right]==nums[right-1])
{
right--;
}
while(left<right&&nums[left]==nums[left+1])
{
left++;
}
right--;
left++;
}
}
}
}
return ans;
}
};