1.题目
- 和为K的子数组
2.思路
利用HASH
3.题目1072
题目
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarray-sum-equals-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
利用HASH
解答
//#include "uthash.h"
typedef struct {
int ikey;
int nums;
UT_hash_handle hh;
} my_struct;
my_struct* g_user = NULL;
int FindNumsFromHash(int ikey)
{
my_struct* s = NULL;
HASH_FIND_INT(g_user, &ikey, s);
if (s == NULL) {
return 0;
}
return s->nums;
}
void AddNumsToHash(int ikey)
{
my_struct* s = NULL;
HASH_FIND_INT(g_user, &ikey, s);
if (s == NULL) {
s = (my_struct*)malloc(sizeof(my_struct));
s->ikey = ikey;
s->nums = 0;
HASH_ADD_INT(g_user, ikey, s);
}
(s->nums)++;
}
int subarraySum(int* nums, int numsSize, int k){
g_user = NULL;
int sum = 0;
int output = 0;
int i;
AddNumsToHash(0);
for (i = 0; i < numsSize; i++) {
sum += nums[i];
output += FindNumsFromHash(sum - k);
AddNumsToHash(sum);
}
return output;
}