Leetcode 3729. Count Distinct Subarrays Divisible by K in Sorted Array

  • [Leetcode 3729. Count Distinct Subarrays Divisible by K in Sorted Array](#Leetcode 3729. Count Distinct Subarrays Divisible by K in Sorted Array)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

对这一题而言,如果不用考虑去重,那么显然我们只需要求出给定数组的前序和数组,然后将其元素按照其对 k k k的余数进行统计,那么对于其答案就是:
a n s w e r = ∑ i = 0 k c i ∗ ( c i − 1 ) 2 answer = \sum\limits_{i=0}^{k} \frac{c_i * (c_i-1)}{2} answer=i=0∑k2ci∗(ci−1)

其中, c i c_i ci表示余数为 i i i时的前序和的个数。

但是这里会有重复的情况,因此,我们需要去除掉这里多算的所有重复情况的个数。由于题目中已知数组是非递减的,因此,如果满足有两个子数组 ( n i ⋯ n j ) (n_i \cdots n_j) (ni⋯nj)与 ( n l ⋯ n r ) (n_l \cdots n_r) (nl⋯nr)完全相同,那么必有这些数的元素必然完全相同。

因此,我们只需要找出所有连续的相同元素的子串,考虑其中会产生多少个重复计算的数组个数即可。而要使得若干个相同元素的和被 k k k整除,那么其连续的个数必然为 k k k与 k k k和该元素的最大公约数的除数的倍数。而其被多记的次数就是该数组的长度减去对应的倍数的个数。

2. 代码实现

我们将其翻译为python代码语言就是:

python 复制代码
class Solution:
    def numGoodSubarrays(self, nums: List[int], k: int) -> int:
        n = len(nums)
        cumsum = list(accumulate(nums, initial=0))
        reminders = [x%k for x in cumsum]
        cnt = Counter(reminders)
        ans = sum(x * (x-1) // 2 for x in cnt.values())
        idx = 0
        while idx < n:
            rb = bisect.bisect_right(nums, nums[idx])
            m = rb - idx
            if k == 1:
                ans -= m * (m+1) // 2 - m
            else:
                l = k // gcd(k, nums[idx])
                for i in range(l, m, l):
                    ans -= m-i
            idx = rb
        return ans

提交代码评测得到:耗时311ms,占用内存41.28MB。

相关推荐
hanlin035 分钟前
刷题笔记:力扣第206题-反转链表
笔记·leetcode·链表
闪电悠米22 分钟前
力扣hot100-240.搜索二维矩阵2-单调性剪枝详解
数据结构·算法·leetcode·矩阵·哈希算法
yyds_yyd_1008615 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
玖玥拾18 小时前
LeetCode 26 删除有序数组中的重复项
算法·leetcode
白白白小纯21 小时前
算法篇—返回倒数第k个节点
c语言·数据结构·算法·leetcode
退休倒计时21 小时前
【复习】LeetCode 二叉树DFS TypeScript
算法·leetcode·typescript·深度优先
白白白小纯1 天前
算法篇—链表的中间节点
c语言·数据结构·算法·leetcode
Frostnova丶1 天前
(19)LeetCode 54. 螺旋矩阵
算法·leetcode·矩阵
Frostnova丶1 天前
(18)LeetCode 73. 矩阵置零
算法·leetcode·矩阵
番茄撒旦在上1 天前
LeetCode 98.验证二叉搜索树-Medium
算法·leetcode