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 c : nums3)
{
for(int d : nums4)
{
if(umap.find(0 - (c + d)) != umap.end())
{
count += umap[0 - (c + d)];
}
}
}
return count;
}
};
使用哈希法的经典题目!
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26] = {0};
if(ransomNote.size() > magazine.size())
{
return false;
}
for(int i = 0;i < magazine.length();i++)
{
record[magazine[i] - 'a']++;
}
for(int j = 0;j < ransomNote.length();j++)
{
record[ransomNote[j] - 'a']--;
if(record[ransomNote[j] - 'a'] < 0)
{
return false;
}
}
return true;
}
};
使用map的空间消耗要比数组大,因为map要维护红黑树或者哈希表,而且还要做哈希函数,是费时的。数组更加简单直接有效!
.length
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(),nums.end());
for(int i = 0;i < nums.size();i++)
{
if(nums[i] > 0)
{
return result;
}
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
{
result.push_back(vector<int>{nums[i], nums[left], nums[right]});
// 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
while(right > left && nums[right] == nums[right - 1]) right --;
while(right > left && nums[left] == nums[left + 1]) left ++;
//legft + 1
right --;
left ++;
}
}
}
return result;
}
};
不可以包含重复的三元组,去重
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;
}
};
剪枝、去重、二级剪枝、二级去重 >=0 (long)