Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 153688e

Browse files
AC 560
1 parent cb8a4a8 commit 153688e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎c/500-599/560-subarray-sum-equals-k.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /