[Prefix sum] 974. Sum of subarrays divisible by K

insert image description here
Halo, this is Ppeua. Usually, I mainly update C++, data structure algorithm, Linux and ROS... If you are interested, follow me bua!

974. Sum Subarrays Divisible by K

insert image description here

topic:

insert image description here

Example:

insert image description here

answer:

This question is highly similar to 560. The sum is a subarray of K

Similarly, this question uses the theorem of the prefix sum. When (pre[i]-pre[j-1]) mod k==0, it is the answer you are looking for.

Do a simple transformation of this formula. Then you can get. Pre[i] mod k == pre[j-1] mod k is the answer you are looking for.

Also use hash to store each answer.

The final answer is the sum of the number of qualified sub-arrays with each position as the end. A boundary condition that needs to be noted is that we need to initialize the hash table and record the case of mp[0]=1, thus considering the case that the prefix sum itself is divisible by k.

Since C++ does not have a modulo operation for negative numbers, we need to process the modulus of negative numbers , as follows:

The result of (sum%k) may be negative, at this time, the following processing is performed (sum%k+k)%k,

Even if it is a negative number that is much smaller than K, after it is congruent to K, the absolute value of its negative congruence value is smaller than K, so after adding K, it is the congruence value of its positive number to K.

for example:

(-33%5+5)%5=2

code:

class Solution {
    
    
public:
    int subarraysDivByK(vector<int>& nums, int k) {
    
    
        for(int i=1;i<nums.size();i++)
        {
    
    
            nums[i]+=nums[i-1];
        }
        unordered_map<int,int>map;
        map[0]=1;
        int res=0;
        for(int i=0;i<nums.size();i++)
        {
    
    
            int models=((nums[i]%k+k)%k);
            if(map.find(models)!=map.end())
            {
    
    
                res+=map[models];
            }
            map[models]++;
        }
        return res;
    }
};

class Solution {
public:
int subarraysDivByK(vector& nums, int k) {
for(int i=1;i<nums.size();i++)
{
nums[i]+=nums[i-1];
}
unordered_map<int,int>map;
map[0]=1;
int res=0;
for(int i=0;i<nums.size();i++)
{
int models=((nums[i]%k+k)%k);
if(map.find(models)!=map.end())
{
res+=map[models];
}
map[models]++;
}
return res;
}
};

Guess you like

Origin blog.csdn.net/qq_62839589/article/details/132011580