File tree 1 file changed +78
-0
lines changed
1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ #define INIT_HASH_SIZE 4096
2
+
3
+ // Represent an element in a hash table.
4
+ typedef struct Hash {
5
+ int key ;
6
+ int count ;
7
+ struct Hash * next ;
8
+ } Hash ;
9
+
10
+ Hash * InitHash () {
11
+ Hash * h = (Hash * )calloc (INIT_HASH_SIZE , sizeof (Hash ));
12
+ assert (h );
13
+ return h ;
14
+ }
15
+
16
+ Hash * NewHash (int key ) {
17
+ Hash * h = (Hash * )malloc (sizeof (Hash ));
18
+ assert (h );
19
+ h -> key = key ;
20
+ h -> count = 1 ;
21
+ h -> next = NULL ;
22
+ return h ;
23
+ }
24
+
25
+ int HashKey (int key ) {
26
+ while (key < 0 ) key += INIT_HASH_SIZE ;
27
+ return (key % INIT_HASH_SIZE );
28
+ }
29
+
30
+ void AddHash (Hash * root , int key ) {
31
+ assert (root );
32
+ Hash * h = & root [HashKey (key )];
33
+ if (h -> key == 0 && h -> count == 0 ) {
34
+ h -> key = key ;
35
+ h -> count = 1 ;
36
+ } else if (h -> key == key ) {
37
+ h -> count ++ ;
38
+ } else {
39
+ while (h ) {
40
+ if (h -> key == key ) {
41
+ h -> count ++ ;
42
+ return ;
43
+ } else if (!h -> next ) {
44
+ h -> next = NewHash (key );
45
+ return ;
46
+ }
47
+ h = h -> next ;
48
+ }
49
+ }
50
+ }
51
+
52
+ // If hash not round return 0 on purpose.
53
+ int GetHash (Hash * root , int key ) {
54
+ Hash * h = & root [HashKey (key )];
55
+ while (h ) {
56
+ if (h -> key == key ) {
57
+ return h -> count ;
58
+ }
59
+ h = h -> next ;
60
+ }
61
+ return 0 ;
62
+ }
63
+
64
+ int subarraySum (int * nums , int numsSize , int k ){
65
+ Hash * hash = InitHash ();
66
+ int sum = 0 ;
67
+ int res = 0 ;
68
+ int r = 0 ;
69
+
70
+ AddHash (hash , 0 );
71
+ for (int i = 0 ; i < numsSize ; i ++ ){
72
+ sum += nums [i ];
73
+ res += GetHash (hash , sum - k );
74
+ AddHash (hash , sum );
75
+ }
76
+
77
+ return res ;
78
+ }
You can’t perform that action at this time.
0 commit comments