leetcode 974. 和可被 K 整除的子数组

leetcode 974. 和可被 K 整除的子数组

题目详情

题目链接
给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。

  • 示例:
    输入:A = [4,5,0,-2,-3,1], K = 5
    输出:7
    解释:
    有 7 个子数组满足其元素之和可被 K = 5 整除:
    [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

提示:

  • 1 <= A.length <= 30000
  • -10000 <= A[i] <= 10000
  • 2 <= K <= 10000

我的代码

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        int len = A.size();
        int res = 0;
        vector<int> results(len, 0);
        for (int i = len - 1; i >= 0; --i) {
            int sum = 0;
            for (int j = i; j < len; ++j) {
                sum += A[j];
                if (sum % K) {
                    results[i] += 0;
                } else {
                    results[i] += 1 + ((j == len - 1)? 0: results[j + 1]);
                    break;
                }
            }
            res += results[i];
        }
        return res;
    }
};

我的成绩

执行结果:超出时间限制

一些想法

本道题我使用了相当于暴力的方法,但是超出了时间限制,差最后一个测试用例没能通过。。。

执行用时为 36 ms 的范例

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        int N = A.size();
        if (N < 1 || K < 2) return 0;
        int ans = 0;
        int sums[N + 1];
        int counts[K];
        memset(sums, 0, sizeof(sums));
        memset(counts, 0, sizeof(counts));
        sums[0] = 0;

        for (int i = 1; i < N + 1; ++i) {
            sums[i] = sums[i - 1] + A[i - 1];
        }

        for (int i = 0; i < N + 1; ++i) {
            counts[(sums[i] % K + K) % K]++;
        }

        for (int i = 0; i < K; ++i) {
            if (counts[i] > 1) {
                ans += counts[i] * (counts[i] - 1) / 2;
            }
            
        }

        return ans;
    }
};

思考

参见官方解答

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值