560. Subarray Sum Equals K

记录前面的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 }

 

转载于:https://www.cnblogs.com/goPanama/p/9828090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值