Leetcode 974. Subarray Sums Divisible by K
2023-01-19 16:26 作者:您是打尖兒還是住店呢 | 我要投稿
Given an integer array?nums
?and an integer?k
, return?the number of non-empty?subarrays?that have a sum divisible by?k
.
A?subarray?is a?contiguous?part of an array.
?
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5Output: 7Explanation: 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]
Example 2:
Input: nums = [5], k = 9Output: 0
?
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
利用前綴和,求出余數(shù),然后把余數(shù)放到map 中,后續(xù)根據(jù)map的value,任取2個(gè)相同的key的對(duì)應(yīng)值,也就是C(n,2)-(n*(n-1)/2)了,但是不能忽略余數(shù)為0的值,需要單獨(dú)加一次、
其他的直接取2個(gè)就可以,但是余數(shù)為0的,自己就能可以的,所以要加上;
Accepted
148.7K
Submissions
276.3K
Acceptance Rate
53.8%
標(biāo)簽: