👨🏫 题目地址
🍻 AC code
class Solution {
public int subarraySum(int[] nums, int k)
{
int ans = 0;
int n = nums.length;
int[] s = new int[n + 1];// 前缀和
s[0] = 0;
s[1] = nums[0];
for (int i = 2; i <= n; i++)
s[i] = s[i - 1] + nums[i - 1];
for (int l = 1; l <= n; l++)// 子数组左边界
for (int r = l; r <= n; r++)// 子数组右边界
{
int x = s[r] - s[l - 1];
if (x == k)
ans++;
}
return ans;
}
}