https://leetcode.com/problems/subarray-sums-divisible-by-k
974. Subarray Sums Divisible by K
給定一數列nums與整數k
請回傳能被k整除的子序列和之非空子序列數量
此子序列必須是nums的連續部分
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Example 2:
Input: nums = [5], k = 9
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
思路:
這題就昨天那題的變形
昨天用集合紀錄前綴和
今天需要知道子序列數量 所以要改用哈希表
哈希表紀錄該前綴和出現幾次
把它加到result再回傳就結束了
Python Code:
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
nums.insert(0,0)
prefix = defaultdict(int)
prefix[0] = 1
result = 0
for i in range(1,len(nums)):
nums[i] = (nums[i]+nums[i-1])%k
result += prefix[nums[i]]
prefix[nums[i]] += 1
return result