Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.數組
Example 1:code
Input: A = [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]leetcode
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/subarray-sums-divisible-by-kget
1.負數求餘
Sum = ((Sum % Mod) + Mod) % Mod;
2.同餘定理應用
子數組和可否被K整除 轉化爲
(preSum[j] - preSum[i-1]) mod K == 0
根據同餘定理,轉化爲
preSum[j] mod K == preSum[i-1] mod K
it
class Solution { public: int subarraysDivByK(vector<int>& A, int K) { map <int,int> Map = {{0 , 1}}; //預置邊界狀況,第0項爲1 int ans = 0; int preSum = 0; for (int elem: A){ preSum += elem; preSum = ((preSum % K) + K) % K; //負數取模的處理 ans += Map[preSum]; Map[preSum]++; } return ans; } };