-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0350IntersectionOfTwoArraysii.java
86 lines (74 loc) · 2.45 KB
/
_0350IntersectionOfTwoArraysii.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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.heatwave.leetcode.problems;
import java.util.*;
public class _0350IntersectionOfTwoArraysii {
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> ans = new LinkedList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int n = nums1.length, m = nums2.length;
int left = 0, right = 0;
while (left < n && right < m) {
int l = nums1[left], r = nums2[right];
if (l == r) {
ans.add(l);
left++;
right++;
} else if (l > r) {
right++;
} else {
left++;
}
}
return ans.stream().mapToInt(Integer::valueOf).toArray();
}
}
class SolutiuonHashMap {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> ans = new LinkedList<>();
Map<Integer, Integer> map = new HashMap<>();
int n = nums1.length, m = nums2.length;
int[] longer, shorter;
if (n > m) {
longer = nums1;
shorter = nums2;
} else {
longer = nums2;
shorter = nums1;
}
for (int i : shorter) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
for (int i : longer) {
Integer count = map.get(i);
if (count != null && count != 0) {
ans.add(i);
map.put(i, count - 1);
}
}
return ans.stream().mapToInt(Integer::valueOf).toArray();
}
}
class SolutionDoublePoint {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> ans = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int n = nums1.length, m = nums2.length;
int left = 0, right = 0;
while (left < n && right < m) {
int l = nums1[left], r = nums2[right];
if (l == r) {
ans.add(l);
left++;
right++;
} else if (l > r) {
right++;
} else {
left++;
}
}
return ans.stream().mapToInt(Integer::valueOf).toArray();
}
}
}