Skip to content

Commit 70d2158

Browse files
committed
issue #21 350-Done
1 parent 35e2734 commit 70d2158

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package leetcodeEasyLevel;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class _0350IntersectionofTwoArraysII {
8+
9+
public static int[] intersect(int[] nums1, int[] nums2) {
10+
// Runtime 2 ms Memory 39.1 MB
11+
List<Integer> ans = new ArrayList<>();
12+
13+
Arrays.sort(nums1);
14+
Arrays.sort(nums2);
15+
16+
int i = 0;
17+
int j = 0;
18+
19+
while (i < nums1.length && j < nums2.length) {
20+
if (nums1[i] == nums2[j]) {
21+
ans.add(nums1[i]);
22+
i++;
23+
j++;
24+
} else if (nums1[i] < nums2[j]) {
25+
i++;
26+
} else {
27+
j++;
28+
}
29+
}
30+
31+
//convert to int array
32+
int[] arr = new int[ans.size()];
33+
int k = 0;
34+
for (int num : ans) {
35+
arr[k++] = num;
36+
}
37+
return arr;
38+
}
39+
40+
public static void main(String[] args) {
41+
int[] nums1 = {1, 2, 2, 1};
42+
int[] nums2 = {2, 2};
43+
int[] nums3 = {4, 9, 5};
44+
int[] nums4 = {9, 4, 9, 8, 4};
45+
System.out.println(Arrays.toString(intersect(nums1, nums2)));
46+
System.out.println(Arrays.toString(intersect(nums3, nums4)));
47+
}
48+
}

0 commit comments

Comments
 (0)