记录前面的sum https://leetcode.com/problems/subarray-sum-equals-k/discuss/102106/Java-Solution-PreSum-+-HashMap
1 class Solution { 2 public int subarraySum(int[] nums, int k) { 3 if(nums.length == 0) return 0; 4 int count = 0; 5 for(int i = 0; i < nums.length; i++){ 6 if(nums[i] == k){ 7 count++; 8 } 9 int j = i+1; 10 int sum = nums[i]; 11 while(j < nums.length){ 12 sum += nums[j]; 13 if(sum == k){ 14 count++; 15 j++; 16 }else{ 17 j++; 18 } 19 } 20 21 } 22 return count; 23 } 24 } 25 26 27 //New 28 class Solution { 29 public int subarraySum(int[] nums, int k) { 30 if(nums.length == 0) return 0; 31 Map<Integer, Integer> map = new HashMap<>(); 32 int res = 0; 33 int sum = 0; 34 map.put(0, 1); 35 for(int i = 0; i < nums.length; i++){ 36 sum += nums[i]; 37 if(map.containsKey(sum - k)){ 38 res += map.get(sum - k); 39 } 40 map.put(sum, map.getOrDefault(sum, 0) + 1); 41 } 42 return res; 43 } 44 }