FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/SubArraySubK.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
SubArraySubK.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
46 lines (39 loc) · 1.25 KB
Breadcrumbs
coding-Interview
/
SubArraySubK.java
Copy path
File metadata and controls
46 lines (39 loc) · 1.25 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// https://leetcode.com/problems/subarray-sum-equals-k/
//
class
Solution
{
public
int
subarraySum
(
int
[]
nums
,
int
k
) {
int
n
=
nums
.
length
;
int
sum
=
0
;
int
count
=
0
;
HashMap
<
Integer
,
Integer
>
map
=
new
HashMap
<>();
map
.
put
(
0
,
1
);
// one way to count 0 sum is before start []
for
(
int
i
=
0
;
i
<
n
;
i
++){
sum
+=
nums
[
i
];
int
diff
=
sum
-
k
;
//if this value is seen then we have a cont sub array with sum = k
if
(
map
.
containsKey
(
sum
-
k
)){
count
+=
map
.
get
(
sum
-
k
);
}
map
.
put
(
sum
,
map
.
getOrDefault
(
sum
,
0
)+
1
);
}
return
count
;
}
}
// Not optimized
class
Solution2
{
public
int
subarraySum
(
int
[]
nums
,
int
k
) {
int
[]
sums
=
new
int
[
nums
.
length
+
1
];
sums
[
0
] =
0
;
for
(
int
i
=
1
;
i
<=
nums
.
length
;
i
++){
//1 to n included due to sum array is updating
sums
[
i
] =
sums
[
i
-
1
] +
nums
[
i
-
1
];
}
int
count
=
0
;
for
(
int
i
=
0
;
i
<
nums
.
length
;
i
++){
for
(
int
end
=
i
+
1
;
end
<
sums
.
length
;
end
++){
if
(
sums
[
end
] -
sums
[
i
] ==
k
){
count
++;
}
}
}
return
count
;
}
}
Back
|
FazBrowse Home
|
New Git URL