Skip to content

Latest commit

 

History

History
62 lines (35 loc) · 1.69 KB

0523-continuous-subarray-sum.adoc

File metadata and controls

62 lines (35 loc) · 1.69 KB

523. Continuous Subarray Sum

{leetcode}/problems/continuous-subarray-sum/[LeetCode - Continuous Subarray Sum^]

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.

Example 1:

Input: [23, 2, 4, 6, 7],  k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

Input: [23, 2, 6, 4, 7],  k=6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

Note:

  1. The length of the array won’t exceed 10,000.

  2. You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

解题分析

利用同余定理:

{image_attr}

当 \(prefixSums[q]−prefixSums[p]\) 为 \(k\) 的倍数时,\(prefixSums[p]\) 和 \(prefixSums[q]\) 除以 \(k\) 的余数相同。(D瓜哥注:余数相同,则相减之后余数就被减掉了。)因此只需要计算每个下标对应的前缀和除以 \(k\) 的余数即可,使用哈希表存储每个余数第一次出现的下标。

{image_attr}
{image_attr}
{image_attr}
{image_attr}
{image_attr}
link:{sourcedir}/_0523_ContinuousSubarraySum.java[role=include]