|
| 1 | +/* |
| 2 | +560. Subarray Sum Equals K |
| 3 | + |
| 4 | +Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. |
| 5 | + |
| 6 | +Example 1: |
| 7 | +Input:nums = [1,1,1], k = 2 |
| 8 | +Output: 2 |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +Note: |
| 13 | + |
| 14 | +The length of the array is in range [1, 20,000]. |
| 15 | +The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. |
| 16 | +*/ |
| 17 | + |
| 18 | +typedef struct e_s { |
| 19 | + int s; |
| 20 | + int c; |
| 21 | + struct e_s *next; |
| 22 | +} e_t; |
| 23 | + |
| 24 | +#define HF 1021 |
| 25 | +#define HC(S) (((S) % HF) + HF) |
| 26 | + |
| 27 | +typedef struct { |
| 28 | + e_t *e[HF * 2]; |
| 29 | + e_t buff[20000]; |
| 30 | + int n; |
| 31 | +} ht_t; |
| 32 | + |
| 33 | +e_t *lookup(ht_t *ht, int s) { |
| 34 | + e_t *e = ht->e[HC(s)]; |
| 35 | + while (e && e->s != s) e = e->next; |
| 36 | + return e; |
| 37 | +} |
| 38 | +void insert(ht_t *ht, int s) { |
| 39 | + e_t *e = lookup(ht, s); |
| 40 | + if (e) e->c ++; |
| 41 | + else { |
| 42 | + e = &ht->buff[ht->n ++]; |
| 43 | + e->s = s; |
| 44 | + e->c = 1; |
| 45 | + e->next = ht->e[HC(s)]; |
| 46 | + ht->e[HC(s)] = e; |
| 47 | + } |
| 48 | +} |
| 49 | +int count(ht_t *ht, int s) { |
| 50 | + e_t *e = lookup(ht, s); |
| 51 | + if (e) return e->c; |
| 52 | + return 0; |
| 53 | +} |
| 54 | +int subarraySum(int* nums, int numsSize, int k){ |
| 55 | + int i, s, r, n; |
| 56 | + ht_t ht = { 0 }; |
| 57 | + |
| 58 | + n = 0; |
| 59 | + s = 0; |
| 60 | + |
| 61 | + insert(&ht, s); |
| 62 | + |
| 63 | + for (i = 0; i < numsSize; i ++) { |
| 64 | + s += nums[i]; |
| 65 | + |
| 66 | + n += count(&ht, s - k); |
| 67 | + |
| 68 | + insert(&ht, s); |
| 69 | + } |
| 70 | + |
| 71 | + return n; |
| 72 | +} |
| 73 | + |
| 74 | + |
| 75 | +/* |
| 76 | +Difficulty:Medium |
| 77 | + |
| 78 | + |
| 79 | +*/ |
0 commit comments