|
| 1 | +/* |
| 2 | + * Copyright (C) 2020, Saul Lawliet <october dot sunbathe at gmail dot com> |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * 暴力破解, 时间复杂度: O(n^2), 提交后比较耗时. |
| 6 | + * |
| 7 | + * 看了解答方案后, 使用 HashMap 的时间复杂度为: O(n) |
| 8 | + * TODO: 后续引入 HashMap 后再优化 |
| 9 | + */ |
| 10 | + |
| 11 | +#include "c/data-structures/array.h" |
| 12 | +#include "c/test.h" |
| 13 | + |
| 14 | +int subarraySum(int *nums, int numsSize, int k) { |
| 15 | + int count = 0; |
| 16 | + for (int i = 0; i < numsSize; i++) { |
| 17 | + for (int j = i, sum = 0; j < numsSize && sum < k; j++) { |
| 18 | + sum += nums[j]; |
| 19 | + if (sum == k) { |
| 20 | + ++count; |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + return count; |
| 25 | +} |
| 26 | + |
| 27 | +void test(int expect, char *nums, int k) { |
| 28 | + arrayEntry *e = arrayParse1D(nums, ARRAY_INT); |
| 29 | + EXPECT_EQ_INT(expect, subarraySum(arrayValue(e), arraySize(e), k)); |
| 30 | + arrayFree(e); |
| 31 | +} |
| 32 | + |
| 33 | +int main(void) { |
| 34 | + test(2, "[1,1,1]", 2); |
| 35 | + |
| 36 | + return testOutput(); |
| 37 | +} |
0 commit comments