454.四数相加II
对题目理解还是不太够
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;
}
};
383. 赎金信
这题看了哈希表法后觉得还好
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;
}
};
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语句放到外面来单独实现也可以
for(int j = 0; j < ransomNote.size(); j++){
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 and 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 and 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 and nums[k] >= 0) {
break;
}
if(k > 0 and nums[k] == nums[k-1]) {
continue;
}
for(int i = k + 1; i < nums.size(); i++){
if(nums[k] + nums[i] > target and nums[k] + nums[i] > 0){
break;
}
if(i > k + 1 and 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 and nums[right] == nums[right - 1])right--;
while(right > left and nums[left] == nums[left + 1])left++;
right--;
left++;
}
}
}
}
return result;
}
};