Skip to main content

Posts

Showing posts from January, 2023

First blog test...

 Today's leetcode daily question 974. Subarray Sums Divisible by K. The idea is as follow: 1. Calculate the prefix sum, and calculate the remainder of each one with k, store them in an unordered_map. 2. Go through the integer array, calculate the prefix sum for each one, and for each time add up[r] where r is the reminder of prefix sum to the final answer. 3. Remember to up[r]-- after update r, which deletes the unit length subarray of current element. class Solution { public: int subarraysDivByK(vector < int >& nums, int k) { unordered_map < int , int > up; int tmp = 0 ; for ( auto & n : nums){ tmp += n; up[(tmp % k + k) % k] ++ ; } int ret = 0 ,cur = 0 ; int r = (cur % k + k) % k; for ( auto & n : nums){ ret += up[r]; cur += n; r = (cur % k + k) % k; up[r] -- ; } return ret; } };