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 bcc261b

Browse files
560. Subarray Sum Equals K
1 parent 554c9c2 commit bcc261b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/// This function has a time complexity of `O(n)`,
2+
/// where `n` is the length of `nums`. This is because
3+
/// the function iterates through nums once and
4+
/// performs constant time operations on each element.
5+
/// The function also uses a map to store the prefix sum,
6+
/// which has a space complexity of `O(n)` in the worst case,
7+
/// where `n` is the length of `nums`.
8+
9+
class Solution {
10+
int subarraySum(List<int> nums, int k) {
11+
int count = 0;
12+
int sum = 0;
13+
Map<int, int> prefixSum = {0: 1};
14+
15+
for (int i = 0; i < nums.length; i++) {
16+
sum += nums[i];
17+
if (prefixSum.containsKey(sum - k)) {
18+
count += prefixSum[sum - k]!;
19+
}
20+
prefixSum[sum] = (prefixSum[sum] ?? 0) + 1;
21+
}
22+
23+
return count;
24+
}
25+
}
26+
27+
void main(List<String> args) {
28+
print(Solution().subarraySum([-1, -1, 1], 0));
29+
print(Solution().subarraySum([1, 2, 5, 3, 4], 6));
30+
print(Solution().subarraySum([1, 1, 1], 2));
31+
print(Solution().subarraySum([1], 1));
32+
print(Solution().subarraySum([-1, 2, -1, -2, -3], -3));
33+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
560. Subarray Sum Equals K
2+
https://leetcode.com/problems/subarray-sum-equals-k/
3+
4+
Given an array of integers nums and an integer k,
5+
return the total number of subarrays whose sum equals to k.
6+
A subarray is a contiguous non-empty sequence of elements within an array.
7+
8+
9+
Example 1:
10+
11+
Input: nums = [1,1,1], k = 2
12+
Output: 2
13+
14+
Example 2:
15+
16+
Input: nums = [1,2,3], k = 3
17+
Output: 2
18+
19+
20+
Constraints:
21+
22+
1 <= nums.length <= 2 * 104
23+
-1000 <= nums[i] <= 1000
24+
-107 <= k <= 107

0 commit comments

Comments
(0)

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