349. Intersection of Two Arrays
求两个set的交集,注意集合类和数组之间的转换
1.set做法
public int[] intersection(int[] nums1, int[] nums2) {
// add nums1 to set
Set<Integer> set1 = new HashSet<>();
for (int i : nums1) set1.add(i);
// create result set, check if nums2 is in set1
Set<Integer> set = new HashSet<>();
for (int i : nums2) {
if (set1.contains(i)) set.add(i);
}
// create result int[]
int[] res = new int[set.size()];
int j = 0;
for (int i : set) {
res[j++] = i;
}
return res;
}
2.参考350,双指针
public int[] intersection(int[] nums1, int[] nums2) {
// boundary check here
if (nums1 == null || nums2 == null) return new int[]{};
// create result set
Set<Integer> set = new HashSet<>();
// sort
Arrays.sort(nums1);
Arrays.sort(nums2);
// two pointers
int i = 0; int 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++;
}
}
// copy set to res[]
int[] res = new int[set.size()];
int k = 0;
for (int num : set) {
res[k++] = num;
}
return res;
}
3.调api,求集合交集,慢
return list(set(nums1) & set(nums2))
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for (int num : nums1) set1.add(num);
for (int num : nums2) set2.add(num);
set1.retainAll(set2);
int i = 0;
int[] res = new int[set1.size()];
for (int num : set1) {
res[i++] = num;
}
return res;
}
retainAll的实现方式,可以看到比contains多了些代码:
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}