链接:https://leetcode.cn/problems/4sum-ii/solution/by-xun-ge-v-1nri/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目![](https://img-blog.csdnimg.cn/e2a61f70d8474db2a173075cd0fe9278.png)
示例![](https://img-blog.csdnimg.cn/5fd990944ff74459b25596cc7cf531d7.png)
思路
解题思路
本题需要使用哈希算法的库进行记录->哈希算法库详解
本题解题步骤:
- 首先定义 一个hash,key放a和b两数之和,value 放a和b两数之和出现的次数。
- 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到hash中。
- 定义int变量count,用来统计a+b+c+d = 0 出现的次数。
- 在遍历大C和大D数组,找到如果 0-(c+d) 在hash中出现过的话,就用count把hash中key对应的value也就是出现次数统计出来。
- 最后返回统计值 count 就可以了
代码
struct my_struct {
int id; /* key */
int val;
UT_hash_handle hh; /* makes this structure hashable */
};
int fourSumCount(int* nums1, int nums1Size, int* nums2, int nums2Size, int* nums3, int nums3Size, int* nums4, int nums4Size){
struct my_struct * hash = NULL;
for(int i = 0; i < nums1Size; i++)
{
for(int j = 0; j < nums2Size; j++)//统计两个数组元素之和,和出现的次数,放到hash中
{
int k = nums1[i] + nums2[j];
struct my_struct * s = NULL;
HASH_FIND_INT(hash, &k, s);
if(s == NULL)
{
s = (struct my_struct *)malloc(sizeof(struct my_struct));
s->id = k;
s->val = 1;
HASH_ADD_INT(hash, id, s);
}
else
{
s->val++;
}
}
}
int count = 0;
for(int i = 0; i < nums3Size; i++)//在遍历大C和大D数组,找到如果 0-(c+d) 在hash中出现过的话,就用count把hash中key对应的value也就是出现次数统计出来
{
for(int j = 0; j < nums4Size; j++)
{
int k = 0 - nums3[i] - nums4[j];
struct my_struct * s = NULL;
HASH_FIND_INT(hash, &k, s);
if(s)
{
count += s->val;
}
}
}
return count;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/4sum-ii/solution/by-xun-ge-v-1nri/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。