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。

相关推荐
熬了夜的程序员4 小时前
【LeetCode】91. 解码方法
算法·leetcode·链表·职场和发展·排序算法
夏鹏今天学习了吗5 小时前
【LeetCode热题100(54/100)】全排列
算法·leetcode·深度优先
DARLING Zero two♡10 小时前
【优选算法】D&C-Mergesort-Harmonies:分治-归并的算法之谐
java·数据结构·c++·算法·leetcode
Q741_14712 小时前
C++ 分治 归并排序 归并排序VS快速排序 力扣 912. 排序数组 题解 每日一题
c++·算法·leetcode·归并排序·分治
熬了夜的程序员1 天前
【LeetCode】89. 格雷编码
算法·leetcode·链表·职场和发展·矩阵
dragoooon341 天前
[优选算法专题四.前缀和——NO.31~32 连续数组、矩阵区域和]
数据结构·算法·leetcode·1024程序员节
熬了夜的程序员1 天前
【LeetCode】87. 扰乱字符串
算法·leetcode·职场和发展·排序算法
·白小白1 天前
力扣(LeetCode) ——15.三数之和(C++)
c++·算法·leetcode
海琴烟Sunshine1 天前
leetcode 268. 丢失的数字 python
python·算法·leetcode