[Swift Weekly Contest 118]LeetCode974. 和可被 K 整除的子数组 | 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,返回其中元素之和可被 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. 1 <= A.length <= 30000
  2. -10000 <= A[i] <= 10000
  3. 2 <= K <= 10000

 368ms 

 1 class Solution {
 2     func subarraysDivByK(_ A: [Int], _ K: Int) -> Int {
 3         var n = A.count
 4         var f:[Int] = [Int](repeating:0,count:K)
 5         f[0] = 1
 6         var x:Int = 0 
 7         for v in A
 8         {
 9             x += v
10             x %= K
11             if x < 0
12             {
13                 x += K
14             }
15             f[x] += 1
16         }
17         var ret:Int = 0
18         for i in  0..<K
19         {
20             ret += f[i]*(f[i]-1)/2
21         }
22         return ret
23     }
24 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10262262.html