• 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;
      }
    }
  • 相关阅读:
    【转】异或
    【算法习题】正整数数组中和为sum的任意个数的组合数
    mysql通过now()获取的时间不对
    【转】CentOS 7系统时间与实际时间差8个小时
    【算法习题】数组中任意2个(3个)数的和为sum的组合
    linux编译安装python3和安装django
    linux常见命令2
    解决安装centos的时候忘记打开网络的问题
    linux常见命令
    python3X和python2X的区别
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10262354.html
Copyright © 2020-2023  润新知