public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<>();
for (int x : nums1) {
set1.add(x);
}
HashSet<Integer> set2 = new HashSet<>();
for (int x : nums2) {
if (set1.contains(x)) {
set2.add(x);
}
}
int[] result = new int[set2.size()];
int i = 0;
for (int x : set2) {
result[i++] = x;
}
return result;
}
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
HashSet<Integer> set = new HashSet<>();
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
set.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[set.size()];
int k = 0;
for (int x : set) {
result[k++] = x;
}
return result;
}