-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayIntersection_2.java
40 lines (37 loc) · 1.13 KB
/
ArrayIntersection_2.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
package com.leetcode.problems;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class ArrayIntersection_2 {
static int[] intersect(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
int i = 0;
int j = 0;
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> resultList = new ArrayList<>();
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
resultList.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]){
i++;
} else {
j++;
}
}
int[] result = new int[resultList.size()];
for (int k = 0; k < resultList.size(); k++) {
result[k] = resultList.get(k);
}
return(result);
}
public static void main(String[] args) {
int[] nums1 = {1,2,2,1};
int[] nums2 = {2,2};
System.out.println(Arrays.toString(intersect(nums1, nums2)));
}
}