-
Notifications
You must be signed in to change notification settings - Fork 51
/
IntersectionofTwoArraysII.java
39 lines (34 loc) · 1.01 KB
/
IntersectionofTwoArraysII.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
package Arrays;
import java.util.ArrayList;
import java.util.Arrays;
public class IntersectionofTwoArraysII {
public static void main(String[] args) {
int[] nums = {2, 3, 5, 2, 5, 6, 7};
int[] nums1 = {2, 2, 3};
int[] ans = intersect(nums, nums1);
System.out.println(Arrays.toString(ans));
}
public static int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
ArrayList<Integer> ans = new ArrayList<>();
int p1 = 0;
int p2 = 0;
while (p1 < nums1.length && p2 < nums2.length) {
if (nums1[p1] < nums2[p2]) {
p1++;
} else if (nums1[p1] > nums2[p2]) {
p2++;
} else {
ans.add(nums1[p1]);
p1++;
p2++;
}
}
int[] result = new int[ans.size()];
for (int i = 0; i < ans.size(); i++) {
result[i] = ans.get(i);
}
return result;
}
}