forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0560-subarray-sum-equals-k.c
78 lines (69 loc) · 1.53 KB
/
0560-subarray-sum-equals-k.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#defineINIT_HASH_SIZE 4096
// Represent an element in a hash table.
typedefstructHash {
intkey;
intcount;
structHash*next;
} Hash;
Hash*InitHash() {
Hash*h= (Hash*)calloc(INIT_HASH_SIZE, sizeof(Hash));
assert(h);
returnh;
}
Hash*NewHash(intkey) {
Hash*h= (Hash*)malloc(sizeof(Hash));
assert(h);
h->key=key;
h->count=1;
h->next=NULL;
returnh;
}
intHashKey(intkey) {
while(key<0) key+=INIT_HASH_SIZE;
return (key % INIT_HASH_SIZE);
}
voidAddHash(Hash*root, intkey) {
assert(root);
Hash*h=&root[HashKey(key)];
if (h->key==0&&h->count==0) {
h->key=key;
h->count=1;
} elseif (h->key==key) {
h->count++;
} else {
while (h) {
if (h->key==key) {
h->count++;
return;
} elseif (!h->next) {
h->next=NewHash(key);
return;
}
h=h->next;
}
}
}
// If hash not round return 0 on purpose.
intGetHash(Hash*root, intkey) {
Hash*h=&root[HashKey(key)];
while(h) {
if (h->key==key) {
returnh->count;
}
h=h->next;
}
return0;
}
intsubarraySum(int*nums, intnumsSize, intk){
Hash*hash=InitHash();
intsum=0;
intres=0;
intr=0;
AddHash(hash, 0);
for(inti=0; i<numsSize; i++){
sum+=nums[i];
res+=GetHash(hash, sum-k);
AddHash(hash, sum);
}
returnres;
}