-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathSubarraySumEqualsK.java
More file actions
68 lines (56 loc) · 1.53 KB
/
SubarraySumEqualsK.java
File metadata and controls
68 lines (56 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Author : Shobhit Behl (LC : shobhitbruh)
class Solution {
public int subarraySum(int[] nums, int k) {
HashMap<Integer,Integer> hs=new HashMap<>();
hs.put(0,1);
int c=0;
int[] ts=new int[nums.length];
for(int i=0;i<nums.length;i++){
ts[i]=nums[i];
if(i>0){
ts[i]+=ts[i-1];
}
if(hs.containsKey(ts[i]-k)){
c+=hs.get(ts[i]-k);
}
hs.put(ts[i],hs.getOrDefault(ts[i],0)+1);
}
return c;
}
}
// @saorav21994
// TC : O(n)
// SC : O(n)
/*
basic concept -> if cumulative_sum(num[i]) - cumulative_sum(num[j]) == k then the sum of numbers between i and j is k. so c_sum(num[i])-k = c_sum(num[j]) -> which means
frequency of curSum-k will give the number of subarray(s) till this index with sum=k.
*/
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int curSum = 0;
int res = 0;
map.put(0, 1);
for (int n : nums) {
curSum += n;
res += map.getOrDefault(curSum-k, 0);
map.put(curSum, map.getOrDefault(curSum, 0) + 1);
}
return res;
}
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0,1);
int ans = 0;
int sum = 0;
for(int i =0;i<nums.length;i++){
sum += nums[i];
if(map.containsKey(sum- k)){
ans += map.get(sum-k);
}
map.put(sum, map.getOrDefault(sum,0)+1);
}
return ans;
}
}