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 a : nums1) {
for (int b : nums2) {
map[a + b]++;
}
}
int count = 0;
for (int c : nums3) {
for (int d : nums4) {
if (map.find(0 - (c + d)) != map.end()) {
count += map[0 - (c + d)];
}
}
}
return count;
}
};
383. 赎金信
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for (int i = 0; i < magazine.length(); i++) {
for (int j = 0; j < ransomNote.length(); j++) {
if (magazine[i] == ransomNote[j])
ransomNote.erase(ransomNote.begin() + j);
}
}
if (ransomNote.length() == 0) {
return true;
}
return false;
}
};
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.size(); i++) {
record[magazine[i] - 'a'] ++;
}
for (int j = 0; j < ransomNote.size(); j++) {
record[ransomNote[j] - 'a'] --;
if (record[ransomNote[j] - 'a'] < 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 (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]});
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;
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;
}
};