给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
说明:
- 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
- 我们可以不考虑输出结果的顺序。
进阶:
- 如果给定的数组已经排好序呢?你将如何优化你的算法?
- 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
- 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
哈希映射
使用HashMap跟踪每个数字出现的次数。
先将第一个数组保存到hashMap中,key为值,value为值出现的次数。在循环第二个数组,每当第二个数组的数次在hashMap中出现一次,就将hashMap对应值的value-1。
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return intersect(nums2, nums1);
}
HashMap<Integer, Integer> nums1Map = new HashMap<>(nums1.length);
for (Integer currentNum : nums1) {
nums1Map.put(currentNum, nums1Map.getOrDefault(currentNum, 0) + 1);
}
List<Integer> result = new ArrayList<>();
for (int currentNum : nums2) {
if (nums1Map.containsKey(currentNum)) {
result.add(currentNum);
Integer sum = nums1Map.get(currentNum);
if (sum == 1) {
nums1Map.remove(currentNum);
} else {
nums1Map.put(currentNum, sum - 1);
}
}
}
return list2Array(result);
}
private int[] list2Array(List<Integer> result) {
int[] resArray = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
resArray[i] = result.get(i);
}
return resArray;
}
- 时间复杂度:O(m+n) 两个数组的每一个数字都被遍历一次
- 空间复杂度:O(min(m,n)) 对较小的数组使用了哈希映射
排序
在两个数组是有序的情况下推荐使用本方法,或者现将有数组排序,需要加上排序的时间复杂度
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> temp = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
temp.add(nums1[i]);
i++;
j++;
continue;
}
if (nums1[i] > nums2[j]) {
j++;
} else {
i++;
}
}
int[] result = new int[temp.size()];
for (int k = 0; k < temp.size(); k++) {
result[k] = temp.get(k);
}
return result;
}
- 时间复杂度:O(n logn + m logm),对两个数组进行排序并遍历一次
- 空间复杂度:O(1) 没有使用额外空间