-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIntersectionOfTwoArrays2.java
More file actions
69 lines (57 loc) · 1.86 KB
/
IntersectionOfTwoArrays2.java
File metadata and controls
69 lines (57 loc) · 1.86 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
69
package array;
import java.util.*;
/**
* Description: https://leetcode.com/problems/intersection-of-two-arrays-ii
* Difficulty: Easy
*/
public class IntersectionOfTwoArrays2 {
/**
* Time complexity: O(m + n)
* Space complexity: O(min(m, n))
*/
public int[] intersectViaFreqMap(int[] small, int[] large) {
if (small.length > large.length) {
return intersectViaFreqMap(large, small); // to save memory on freqMap
}
Map<Integer, Integer> freqMap = buildFrequencyMap(small);
List<Integer> intersection = new ArrayList<>();
for (int num : large) {
int count = freqMap.getOrDefault(num, 0);
if (count > 0) {
intersection.add(num);
freqMap.merge(num, -1, Integer::sum);
}
}
return intersection.stream().mapToInt(v -> v).toArray();
}
private Map<Integer, Integer> buildFrequencyMap(int[] nums) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.merge(num, 1, Integer::sum);
}
return freqMap;
}
/**
* Time complexity: O(nlog n + mlog m)
* Space complexity: O(log n + log m)
*/
public int[] intersectViaSorting(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int first = 0;
int second = 0;
List<Integer> intersection = new ArrayList<>();
while (first < nums1.length && second < nums2.length) {
if (nums1[first] > nums2[second]) {
second++;
} else if (nums1[first] < nums2[second]) {
first++;
} else {
intersection.add(nums1[first]);
first++;
second++;
}
}
return intersection.stream().mapToInt(v -> v).toArray();
}
}