问题:
给定数组,求连续子数组之和能被K整除的,子数组个数。
Example 1: 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] Note: 1 <= A.length <= 30000 -10000 <= A[i] <= 10000 2 <= K <= 10000
解法:
1 class Solution { 2 public: 3 int subarraysDivByK(vector<int>& A, int K) { 4 vector<int> premodcount(K);//prevalue, rescout 5 int res=0; 6 int presum=0; 7 premodcount[0]=1; 8 for(int i=0; i<A.size(); i++){ 9 presum=(presum+A[i]%K+K)%K; 10 res+=premodcount[presum]; 11 premodcount[presum]++; 12 } 13 return res; 14 } 15 };
974. Subarray Sums Divisible by K
原文:https://www.cnblogs.com/habibah-chang/p/12997066.html