【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 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章