454.四数相加II
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int,int> map;
for(int num1:nums1){
for(int num2:nums2){
map[num1+num2]++;
}
}
int count = 0;
for(int num3:nums3){
for(int num4:nums4){
if(map.find(0-(num3+num4))!= map.end()){
count += map[0-(num3+num4)];
}
}
}
return count;
}
};
383. 赎金信
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int hashset[26] = {0};
for(int i = 0;i < magazine.size();i++){
hashset[magazine[i]-'a']++;
}
for(int i = 0;i < ransomNote.size();i++){
hashset[ransomNote[i]-'a']--;
}
for(int i = 0;i < 26;i++){
if(hashset[i] < 0){
return false;
}
}
return true;
}
};
15. 三数之和
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(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;
}
};
18. 四数之和
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
if(nums.size()<4)return result;
sort(nums.begin(),nums.end());
for(int i = 0;i < nums.size() - 3;++i){
if(i > 0 && nums[i] == nums[i-1])continue;
for(int j = nums.size()-1;j > i+2;--j){
if(j < nums.size()-1 && nums[j] == nums[j+1])continue;
long long sum = nums[i] + nums[j];
int left = i + 1;
int right = j - 1;
while(left < right){
sum += nums[left] + nums[right];
if(sum > target)--right;
else if(sum < target)++left;
else{
result.push_back(vector<int>{nums[i],nums[left],nums[right],nums[j]});
while(right > left && nums[right] == nums[right-1])--right;
while(right > left && nums[left] == nums[left+1])++left;
--right;
++left;
}
sum = nums[i] + nums[j];
}
}
}
return result;
}
};
今天时间有点赶了,过几天再回来补思路和感想。