File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ #define FREE_AND_RETURN (x , y ) \
2
+ free(x); \
3
+ return y;
4
+
5
+ bool checkSubarraySum (int * nums , int numsSize , int k ){
6
+ unsigned int * sums = NULL ;
7
+ int i , j ;
8
+
9
+ // Early return edge cases.
10
+ if (numsSize < 2 ) {
11
+ return false;
12
+ }
13
+ if (k == 1 ) {
14
+ return true;
15
+ }
16
+
17
+ sums = (unsigned int * )malloc (numsSize * sizeof (unsigned int ));
18
+ sums [0 ] = nums [0 ];
19
+ for (i = 1 ; i < numsSize ; i ++ ) {
20
+ // Return true, when there are two continuous nums are times of k.
21
+ if (nums [i ] % k == 0 && nums [i - 1 ] % k == 0 ) {
22
+ FREE_AND_RETURN (sums , true);
23
+ }
24
+
25
+ sums [i ] = nums [i ] + sums [i - 1 ];
26
+
27
+ // Return true, when the current subarray sum is times of k.
28
+ if (sums [i ] % k == 0 ) {
29
+ FREE_AND_RETURN (sums , true);
30
+ }
31
+ }
32
+
33
+ for (i = 0 ; i < numsSize ; i ++ ) {
34
+ if (sums [i ] < k ) {
35
+ continue ;
36
+ }
37
+
38
+ for (j = 0 ; j < i - 1 ; j ++ ) {
39
+ // Return true, when the any subarray sum is times of k.
40
+ if ((sums [i ] - sums [j ]) % k == 0 ) {
41
+ FREE_AND_RETURN (sums , true);
42
+ }
43
+ }
44
+ }
45
+
46
+ FREE_AND_RETURN (sums , false);
47
+ }
You can’t perform that action at this time.
0 commit comments