LC 974. Subarray Sums Divisible by K

Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by 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. 1 <= A.length <= 30000
  2. -10000 <= A[i] <= 10000
  3. 2 <= K <= 10000

用了dp,如果某一个数能被K整除,那么以该位结尾的这样的连续子数组的个数就是前一位dp值+1(新的1是它本身)。

如果不能被K整除,那么就让j从i开始往前遍历,碰到第一个从j到i能被K整除的子数组,那么该位上面的长度就是第j位的dp值加上1,新的1指的是从j到i的子数组。

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        vector<int> dp(A.size(),0);
        vector<int> Bsum(A.size()+1, 0);
        for(int i=0; i<A.size(); i++){
            Bsum[i+1] = Bsum[i] + A[i];
        }
        int ret = 0;
        for(int i=1; i<Bsum.size(); i++){
            if(A[i-1] % K == 0){
                if(i-1 == 0) dp[i-1] = 1;
                else dp[i-1] = dp[i-2] + 1;
                continue;
            }
            int newcnt = 0;
            for(int j=i-1; j>=0; j--){
                //if(Bsum[i] - Bsum[j] == 0) continue;
                if( (Bsum[i] - Bsum[j]) % K == 0) {
                    //cout << i << " " << j << endl;
                  newcnt += dp[j-1] + 1;
                  break;
                }
            }
            dp[i-1] = newcnt;
        }
        for(auto x : dp) ret += x;
        return ret;
    }
};

 

a better solution

count the remainder.

class Solution {
  public int subarraysDivByK(int[] A, int K) {
    Map<Integer,Integer> mp = new HashMap<>();
    mp.put(0,1);
    int prefix = 0, ret = 0;
    for(int a : A){
      prefix += a;
      prefix = (prefix%K+K)%K;
      ret += mp.getOrDefault(prefix, 0);
      mp.put(prefix, mp.getOrDefault(prefix,0)+1);
    }
    return ret;
  }
}

 

posted @ 2019-01-13 13:11  yuxihong  阅读(175)  评论(0编辑  收藏  举报