LeetCode 454. 四数相加 II
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int, int> hash;
for (int i : nums1) {
for (int j : nums2) {
if (hash.count(i + j)) {
hash.at(i + j)++;
}else {
hash.insert(make_pair(i + j, 1));
}
}
}
int res = 0;
for (int i : nums3) {
for (int j : nums4) {
int target = i + j;
if (hash.count(-target)) {
res += hash.at(-target);
}
}
}
return res;
}
};
LeetCode 383. 赎金信
1.哈希表
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> hash;
for (char ch : magazine) {
if (hash.count(ch)) {
hash.at(ch)++;
continue;
}
hash.insert(make_pair(ch, 1));
}
for (char ch : ransomNote) {
if (!hash.count(ch) || hash.at(ch) == 0) {
return false;
}
hash.at(ch)--;
}
return true;
}
};
2.数组充当hash表
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int hash[26] = {0};
for (int i : magazine) {
hash[i - 'a']++;
}
for (int j : ransomNote) {
if (hash[j - 'a']) {
hash[j - 'a']--;
continue;
}
return false;
}
return true;
}
};
LeetCode 15. 三数之和
双指针 && 去重判断
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) {
return res;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1, right = nums.size() - 1;
while (left < right) {
int target = nums[i] + nums[left] + nums[right];
if (target > 0) {
right--;
} else if (target < 0){
left++;
} else {
res.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left+1]) left++;
while(left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
}
}
}
return res;
}
};
LeetCode 18. 四数之和
双重循环 && 双指针
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > target && nums[i] >= 0) {
return res;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] > target && nums[i] + nums[j] >= 0) {
break;
}
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = nums.size() - 1;
while (left < right) {
long temp = (long)nums[i] + nums[j] + nums[left] + nums[right];
if (temp > target) {
right--;
} else if (temp < target) {
left++;
} else {
res.push_back({nums[i], nums[j], nums[left], nums[right]});
while (left < right && nums[right] == nums[right - 1]) right--;
while (left < right && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
}
return res;
}
};