974. 和可被 K 整除的子数组
C代码:哈希表+前缀和
typedef struct{int val;int cnt;UT_hash_handle hh;
} HashTable;int subarraysDivByK(int* nums, int numsSize, int k){HashTable* head = NULL;HashTable* out = NULL;int sum = 0;int cnt = 0;out = (HashTable*)malloc(sizeof(HashTable)); // 0out->val = 0;out->cnt = 1;HASH_ADD_INT(head, val, out);for (int i = 0; i < numsSize; ++i) {sum += nums[i];int val = (sum % k + k) % k; // (sum2-sum1)%k == 0; sum2 % k == sum1%k; 适合整数、但是负数不行 当被除数为负数时取模结果为负数,需要纠正HASH_FIND_INT(head, &val, out);if (out == NULL) {out = (HashTable*)malloc(sizeof(HashTable));out->val = val;out->cnt = 1;HASH_ADD_INT(head, val, out);} else {cnt += out->cnt;out->cnt++; // 叠加次数}}return cnt;
}