leetcode 560. Subarray Sum Equals K

题目

https://leetcode.com/problems/subarray-sum-equals-k/
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Constraints:

The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

思路

记录向前累计和,而后向前查找距离目标k的差值出现多少次,区间问题尽量转换为向前累计和的操作,而不是区间和的问题

源码

class Solution {
public:
    unordered_map<int,int> m;
    int sum[20005];
    int res = 0;
    int subarraySum(vector<int>& nums, int k) {
        sum[0] = 0;
        m[0] = 1;
        for(int i = 1;i <= nums.size();++i){
            int s = sum[i-1]+nums[i-1];
            sum[i] = s;
            int re = s-k;
            if(m.find(re)!=m.end()){
                res+=m[re];
            }
            if(m.find(s)==m.end()){
                m[s]=1;
            }else{
                m[s]++;
            }
        }
        return res;
    }
};

leetcode 974. Subarray Sums Divisible by K 前缀和+同余定理

题目

https://leetcode.com/problems/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 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000

思路

前缀和而后dp同余即可,任意范围的子数组和(i,j] = sum[j]-sum[i],我们要确保他mod K = 0,根据同余定理可知要求 sum[i] mod K == sum[j] mod K 即 sum[i] 同余 sum[j], 所以使用 hashmap 记录余数的个数,后面直接累加

源码

class Solution {
public:
    int sum[30005];
    int res = 0;
    map<int,int> m;
    int subarraysDivByK(vector<int>& A, int K) {
        if(A.size()==0)return res;
        sum[0] = 0;
        m[0] = 1;
        for(int i = 1;i <= A.size();++i){
            sum[i] = sum[i-1]+A[i-1];
            int yu = sum[i]%K;
            if(m.count(yu)==0){
                m[yu] = 1;
            }else{
                m[yu]++;
            }
            res+=(m[yu]-1);
        }
        return res;
    }
};