leetcode | 974. Subarray Sums Divisible by K (subArray系列1)

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]

分析

  • prefix Sum是这类题目的基本技巧
  • prefix Sum之后O(n^2)的暴力枚举,过不了case
  • Time Limit Exceeded解法:
    public int subarraysDivByK(int[] A, int K) {
        int res = 0;
        int len = A.length;
        int[] sum = new int[len];
        for(int i = 0; i < len; i++){
            if (i == 0) sum[i] = A[i];
            else sum[i] = sum[i - 1] + A[i];
        }
        for (int i = 0; i < len; i++) {
            for (int j = i; j < len; j++) {
                int tmp;
                if (i >= 1) tmp = sum[j] - sum[i - 1];
                else tmp = sum[j];
                if (tmp%K == 0) res++;
            }
        }
        return res;
    }

分析

  • 注意到题目的特殊性,满足要求的**sub[i, j]**有如下特点:prefixSum[i’ - 1] % K == prefixSum[j’] % K ; i’ = i + 1, j’ = j + 1(0占位),周赛没有想到这一点
  • 举例:Input: A = [4,5,0,-2,-3,1], K = 5
  • prefixSum = [0, 4, 9, 9, 7, 4, 5] mod = [0, 4, 4, 4, 2, 4, 0] (首位0是占位作用)
  • sub[0, 0] = prefixSum[1] - prefixSum[0];
  • mod为4的索引有4个,[1,2,3,5],有6(1 + 2 + 3)subArray满足题目要求sub[1,2] sub[1,3] sub[1,5] sub[2,3] sub[2,4] sub[3,5]
  • <mod, freq> 来记录相同mod的频率,从而计算结果
    public int subarraysDivByK(int[] A, int K) {
        // [4,5,0,-2,-3,1]
        // [0,4,9,9,7,4,5]
        // [0,4,4,4,2,4,0]
        // <mod, freq>
        HashMap<Integer, Integer> m = new HashMap<>();
        m.put(0, 1);
        int sumMode = 0;
        int res = 0;
        for (int a : A) {
            sumMode = (sumMode + a) % K;
            if (sumMode < 0) {
                sumMode += K;
            }
            int freq = m.get(sumMode) == null ? 0 :  m.get(sumMode);
            res += freq;
            m.put(sumMode, freq + 1);
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值