-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution350_2.java
40 lines (32 loc) · 944 Bytes
/
Solution350_2.java
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
package hash_table_problem;
import java.util.ArrayList;
import java.util.HashMap;
/**
* O(len(nums1) + len(nums2))
* O(len(nums1))
*/
public class Solution350_2 {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> record = new HashMap<>();
for (Integer item:nums1) {
if (!record.containsKey(item)) {
record.put(item, 1);
} else {
record.put(item, record.get(item) + 1);
}
}
ArrayList<Integer> result = new ArrayList<>();
for (Integer item:nums2) {
if (record.containsKey(item) && record.get(item) > 0) {
result.add(item);
record.put(item, record.get(item) - 1);
}
}
int[] res = new int[result.size()];
int i = 0;
for (Integer item:result) {
res[i++] = item;
}
return res;
}
}