zoukankan      html  css  js  c++  java
  • 【leetcode】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

    解题思路:本题需要用到一个数学规律,如果a%c = b%c,那么(a-b)%c=0。我的解法就是从后往前遍历数组,依次累加每个元素的值并记为sum,同时用字典保存sum%K作为key值出现的次数。同时每累加一个元素,只要去字典中查找历史sum%K出现的次数,这个次数就是从以这个元素作为起点满足条件的子数组的个数。特别注意的是,如果sum%K=0,那么表示这个元素本身就满足条件,次数要+1。

    代码如下:

    class Solution(object):
        def subarraysDivByK(self, A, K):
            """
            :type A: List[int]
            :type K: int
            :rtype: int
            """
            dic = {}
            count = 0
            res = 0
            for i in A[::-1]:
                count += i
                if count%K in dic:
                    res += dic[count%K]
                if count % K == 0:
                    res += 1
                dic[count%K] = dic.setdefault(count%K,0)+1
            return res
            
  • 相关阅读:
    Uva 10935 Throwing cards away I
    Uva 3226 Symmetry
    eclipse @ 注释为何一写就报错
    2015省赛小感想
    Zoj 3842 Beauty of Array
    fedora 设置命令别名
    Uva220 Othello
    工作小技巧积累
    SSL介绍与Java实例
    一个完整的SSL连接建立过程
  • 原文地址:https://www.cnblogs.com/seyjs/p/10317990.html
Copyright © 2011-2022 走看看