版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35542218/article/details/79881453
[LeetCode]两个数组的交集 II
给定两个数组,写一个方法来计算它们的交集。
例如:
给定* ***nums1 =[1, 2, 2, 1]
, nums2 =[2, 2]
, 返回[2, 2]
.注意:
- * * 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
- 我们可以不考虑输出结果的顺序。
跟进:
- 如果给定的数组已经排好序呢?你将如何优化你的算法?
- 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
- 如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?
public int[] intersect(int[] nums1, int[] nums2) {
int[] news = new int[0];
if (nums1 == null || nums2 == null) {
return null;
}
if (nums1.length == 0 || nums2.length == 0) {
return news;
}
news = new int[nums1.length];
int[] count = new int[nums1.length];
int index = 0;
for (int i = 0; i < nums2.length; i++) {
for (int j = 0; j < nums1.length; j++) {
if (nums1[j] == nums2[i] && count[j] == 0) {
news[index] = nums1[j];
index++;
count[j] = 1;
break;
}
}
}
int[] ints = new int[index];
for (int i = 0; i < ints.length; i++) {
ints[i] = news[i];
}
return ints;
}