四数相加
class Solution {
public:
int fourSumCount(vector
unordered_map<int, int> umap;
for(int num1 : nums1)
{
for(int num2 : nums2)
{
umap[num1+num2]++;
}
}
int count = 0;
for(int num3 : nums3)
{
for(int num4 : nums4)
{
if(umap.find(0 - num3 - num4) != umap.end())
{
count += umap[0-num3-num4];
}
}
}
return count;
}
};
赎金信
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int s[26] = {0};
for(int i = 0; i < magazine.size(); ++i)
{
s[magazine[i] - 'a']++;
}
for(int i = 0; i < ransomNote.size(); ++i)
{
s[ransomNote[i] - 'a']--;
}
for(int i = 0; i < 26; ++i)
{
if(s[i] < 0)
{
return false;
}
}
return true;
}
};
三数之和
class Solution {
public:
vector<vector
vector<vector
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); ++i)
{
if(nums[i] > 0)
{
return ret;
}
if(i > 0 && nums[i] == nums[i-1])
{
continue;
}
int left = i+1;
int right = nums.size()-1;
while(right > left)
{
if(nums[i] + nums[left] + nums[right] > 0)
{
right--;
}
else if(nums[i] + nums[left] + nums[right] < 0)
{
left++;
}
else
{
ret.push_back(vector
while(right > left && nums[right] == nums[right-1])
{
right--;
}
while(right > left && nums[left] == nums[left+1])
{
left++;
}
right--;
left++;
}
}
}
return ret;
}
};
四数之和
class Solution {
public:
vector<vector
vector<vector
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] >= 0 && nums[i] + nums[j] > target)
{
break;
}
if(j > i + 1 && nums[j] == nums[j-1])
{
continue;
}
int left = j + 1;
int right = nums.size() - 1;
while(right > left)
{
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
{
ret.push_back(vector{nums[i], nums[j], nums[left], nums[right]});
while(left < right && nums[right-1] == nums[right])
{
right--;
}
while(left < right && nums[left] == nums[left+1])
{
left++;
}
right--;
left++;
}
}
}
}
return ret;
}
};