没想到四个数也能用map
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int,int>num;
int count=0;
for(int a:nums1)
{
for(int b:nums2)
num[a+b]++;
}
for(int c:nums3)
{
for(int d:nums4)
{
if(num.find(0-(c+d))!=num.end())
count+=num[0-(c+d)];
}
}
return count;
}
};
容易,想了一下为什么用数组
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26] = {0};
for (int i = 0; i < magazine.length(); i++)
{
record[magazine[i]-'a'] ++;
}
for (int i = 0; i < ransomNote.length(); i++)
{
record[ransomNote[i]-'a']--;
if(record[ransomNote[i]-'a'] < 0)
return false;
}
return true;
}
};
用双指针做了,去重的思想还得再看看
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(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
{
result.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 result;
}
};
没做剪枝
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>>result;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++)
{
if(i>0&&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;
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
{
result.push_back(vector<int>{nums[i],nums[j],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;
}
};