int subarraySum(int* nums, int numsSize, int k)
{
const int N = 1e5 + 3, null = 0x3f3f3f3f;
int preSum = 0, ans = 0;
int h[N], cnt[N];
memset(h, 0x3f, sizeof(h));
memset(cnt, 0, sizeof(cnt));
h[0] = 0, ++cnt[0];
for (int i = 0; i < numsSize; ++i)
{
preSum += nums[i];
int q = preSum - k;
int x = (q % N + N) % N;
while (h[x] != null && h[x] != q)
{
x++;
if (x == N)
{
x = 0;
}
}
if (h[x] != null)
{
ans += cnt[x];
}
x = (preSum % N + N) % N;
while (h[x] != null && h[x] != preSum)
{
x++;
if (x == N)
{
x = 0;
}
}
h[x] = preSum, ++cnt[x];
}
return ans;
}
Leetcode.560和为K的子数组
于 2024-05-10 14:05:01 首次发布