-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathSolution1.java
42 lines (34 loc) · 1.01 KB
/
Solution1.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
41
42
package map;
import java.util.ArrayList;
import java.util.TreeMap;
/**
* Leetcode 350. Intersection of Two Arrays II
* https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
*/
class Solution1 {
public int[] intersect(int[] nums1, int[] nums2) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for (Integer item:nums1) {
if (!map.containsKey(item)) {
map.put(item, 1);
} else {
map.put(item, map.get(item) + 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
for (Integer item:nums2) {
if (map.containsKey(item)) {
list.add(item);
map.put(item, map.get(item) - 1);
if (map.get(item) == 0) {
map.remove(item);
}
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}