【Leetcode】560. 和为K的子数组&974. 和可被 K 整除的子数组(前缀和+哈希表)

 1 public class Solution {
 2     public int subarraySum(int[] nums, int k) {
 3         int count = 0, pre = 0;
 4         HashMap < Integer, Integer > map = new HashMap < > ();
 5         map.put(0, 1);
 6         for (int i = 0; i < nums.length; i++) {
 7             pre += nums[i];
 8             if (mp.containsKey(pre - k))
 9                 count += mp.get(pre - k);
10             mp.put(pre, mp.getOrDefault(pre, 0) + 1);
11         }
12         return count;
13     }
14 }

 1 class Solution {
 2     public int subarraysDivByK(int[] A, int K) {
 3         //记录余数出现的次数
 4         HashMap<Integer, Integer> map = new HashMap<>();
 5         map.put(0,1);
 6         int pre = 0;//前缀和
 7         int ans = 0; 
 8         for(int i = 0; i < A.length; i++){
 9             pre += A[i];
10             int m = (pre % K + K) % K;//余数 (负数处理)
11             int same = map.getOrDefault(m,0);
12             ans += same;
13             map.put(m,same+1);
14         }
15         return ans;
16     }
17 }

猜你喜欢

转载自www.cnblogs.com/xdcat/p/12970855.html