代码随想录算法训练营第37期 第七天 | LeetCode454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
一、454.四数相加II
解题代码C++:
cpp
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int, int> map;
for(int i = 0; i < nums1.size(); i ++)
for(int j = 0; j < nums2.size(); j ++)
map[nums1[i] + nums2[j]] ++;
int cnt = 0;
for(int i = 0; i < nums3.size(); i ++)
for(int j = 0; j < nums4.size(); j ++)
if(map.find(0 - (nums3[i] + nums4[j])) != map.end())
cnt += map[0 - (nums3[i] + nums4[j])];
return cnt;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0454.四数相加II.html
二、383. 赎金信
解题代码C++:
cpp
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for(int i = 0; magazine[i]; i ++)
for(int j = 0; ransomNote[j]; j ++)
{
if(magazine[i] == ransomNote[j])
ransomNote.erase(ransomNote.begin() + j);
}
if(ransomNote.size() == 0) return true;
else return false;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0383.赎金信.html
三、15. 三数之和
解题代码C++:
cpp
class Solution {
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(nums[i] > 0) break;
if(i > 0 && nums[i] == nums[i - 1]) continue;
unordered_set<int> set;
for(int j = i + 1; j < nums.size(); j ++)
{
if(j > i + 2 && nums[j] == nums[j - 1] && nums[j - 1] == nums[j - 2]) continue;
int c = 0 - (nums[i] + nums[j]);
if(set.find(c) != set.end())
{
res.push_back({nums[i], nums[j], c});
set.erase(c);
}
else set.insert(nums[j]);
}
}
return res;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0015.三数之和.html
四、18. 四数之和
解题代码C++:
cpp
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int k = 0; k < nums.size(); k ++)
{
if (nums[k] > target && nums[k] >= 0) break;
if (k > 0 && nums[k] == nums[k - 1]) continue;
for (int i = k + 1; i < nums.size(); i ++)
{
if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) break;
if (i > k + 1 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.size() - 1;
while (right > left)
{
if((long) nums[k] + nums[i] + nums[left] + nums[right] > target) right --;
else if((long) nums[k] + nums[i] + nums[left] + nums[right] < target) left ++;
else
{
result.push_back(vector<int>{nums[k], 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 result;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0018.四数之和.html