题目454
class Solution {
public:
int fourSumCount(vector& A, vector& B, vector& C, vector& D) {
unordered_map<int, int> umap; //key:a+b的数值,value:a+b数值出现的次数
for (int a : A) {
for (int b : B) {
umap[a + b]++;
}
}
int count = 0;
for (int d : D) {
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 A[26]={0};
for(char&c:magazine){
++A[c-‘a’];
}
for(char&c:ransomNote){
if(–A[c-‘a’]<0){
return false;
}
}
return true;
}
};
题目 15
/**
- Return an array of arrays of size *returnSize.
- The sizes of the arrays are returned as *returnColumnSizes array.
- Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int cmp(const void* ptr1, const void* ptr2) {
return ((int)ptr1) > ((int)ptr2);
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
int ans = (int)malloc(sizeof(int*) * 18000);
int ansTop = 0;
//若传入nums数组大小小于3,则需要返回数组大小为0
if(numsSize < 3) {
*returnSize = 0;
return ans;
}
qsort(nums,numsSize,sizeof(int),cmp);//排序
for(int i=0;i<numsSize-2;i++){
if(nums[i]>0) break;
if(i > 0 && nums[i] == nums[i-1])
continue;
int left =i+1;
int right=numsSize-1;
while(left<right){
int sum=nums[i]+nums[left]+nums[right];
if(sum<0){
left++;
}else if(sum>0){
right–;
}else{
int arr=(int)malloc(sizeof(int)*3);
arr[0] = nums[i];
arr[1] = nums[left];
arr[2] = nums[right];
ans[ansTop++] = arr;
while(right > left && nums[right] == nums[right - 1])
right–;
while(left < right && nums[left] == nums[left + 1])
left++;
//更新左右指针
left++;
right–;
}
}
}
*returnSize=ansTop;
*returnColumnSizes=(int*)malloc(sizeof(int)*ansTop);
for(int i=0;i<ansTop;++i){
(*returnColumnSizes)[i]=3;
}
return ans;
}
题目 18
class Solution {
public:
vector<vector> fourSum(vector& nums, int target) {
vector<vector> result;
sort(nums.begin(), nums.end());
for (int k = 0; k < nums.size(); k++) {
// 剪枝处理
if (nums[k] > target && nums[k] >= 0) {
break; // 这里使用break,统一通过最后的return返回
}
// 对nums[k]去重
if (k > 0 && nums[k] == nums[k - 1]) {
continue;
}
for (int i = k + 1; i < nums.size(); i++) {
// 2级剪枝处理
if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) {
break;
}
// 对nums[i]去重
if (i > k + 1 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (right > left) {
// nums[k] + nums[i] + nums[left] + nums[right] > target 会溢出
if ((long) nums[k] + nums[i] + nums[left] + nums[right] > target) {
right--;
// nums[k] + nums[i] + nums[left] + nums[right] < target 会溢出
} 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]});
// 对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;
}
};