-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0349IntersectionOfTwoArrays.java
More file actions
48 lines (43 loc) · 1.36 KB
/
_0349IntersectionOfTwoArrays.java
File metadata and controls
48 lines (43 loc) · 1.36 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
package com.heatwave.leetcode.problems;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class _0349IntersectionOfTwoArrays {
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> ans = new HashSet<>();
Set<Integer> set = new HashSet<>();
for (int i : nums1) {
set.add(i);
}
for (int i : nums2) {
if (set.contains(i)) {
ans.add(i);
}
}
return ans.stream().mapToInt(Integer::valueOf).toArray();
}
}
class SolutionDoublePoint {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> ans = new HashSet<>();
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();
}
}
}