FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/350_Intersection_of_Two_Arrays_II.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
350_Intersection_of_Two_Arrays_II.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
39 lines (32 loc) · 1.18 KB
Breadcrumbs
leetcode
/
java
/
350_Intersection_of_Two_Arrays_II.java
Copy path
File metadata and controls
39 lines (32 loc) · 1.18 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
/*
https://leetcode.com/problems/intersection-of-two-arrays-ii/
Given two arrays, write a function to compute their intersection.
Each element in the result should appear as many times as it shows in both arrays.
Count the frequencies in one array. For each element in other array, if it has a positive count then add to result and
decrement count.
Time - O(m + n)
Space - O(m), count map is size of first array so preferable to count the array with fewer distinct elements.
*/
public
class
Solution
{
public
int
[]
intersect
(
int
[]
nums1
,
int
[]
nums2
) {
HashMap
<
Integer
,
Integer
>
count
=
new
HashMap
<
Integer
,
Integer
>();
ArrayList
<
Integer
>
result
=
new
ArrayList
<
Integer
>();
for
(
int
n
:
nums1
) {
if
(
map
.
containsKey
(
n
)
map
.
put
(
n
,
map
.
get
(
n
) +
1
);
else
map
.
put
(
n
,
1
);
}
for
(
int
n
:
nums2
) {
if
(
map
.
containsKey
(
n
) &&
map
.
get
(
n
) >
0
)
{
result
.
add
(
n
);
map
.
put
(
n
,
map
.
get
(
n
) -
1
);
}
}
int
[]
res
=
new
int
[
result
.
size
()];
for
(
int
i
=
0
;
i
<
result
.
size
();
i
++) {
res
[
i
] =
result
.
get
(
i
);
}
return
res
;
}
}
Back
|
FazBrowse Home
|
New Git URL