|
| 1 | +#defineFREE_AND_RETURN(x,y) \ |
| 2 | +free(x); \ |
| 3 | +return y; |
| 4 | + |
| 5 | +boolcheckSubarraySum(int*nums,intnumsSize,intk){ |
| 6 | +unsignedint*sums=NULL; |
| 7 | +inti,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= (unsignedint*)malloc(numsSize*sizeof(unsignedint)); |
| 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 | +} |