
方法一:哈希表
--单Set
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
for (int num : nums1) {
set.add(num);
}
int size = 0;
for (int num : nums2) {
if (set.contains(num)) {
nums1[size++] = num;
set.remove(num);
}
}
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = nums1[i];
}
return res;
}
}
--双Set
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
for (int num : nums2) {
if (set1.contains(num)) {
set2.add(num);
}
}
int i = 0;
int[] res = new int[set2.size()];
for (int num : set2) {
res[i++] = num;
}
return res;
}
}
方法二:排序+双指针
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
Set<Integer> set = new HashSet<>();
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
set.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int k = 0;
int[] res = new int[set.size()];
for (int num : set) {
res[k++] = num;
}
return res;
}
}