题目:
给定两个数组,写一个方法来计算它们的交集。
例如:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
注意:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
跟进:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?
代码:
package leetCode;
import java.util.Arrays;
/**
* 数组交集II 2018.7.19
*
* @author dhc
*
*/
public class ThreeHundredsAndThirtyFive {
public static int[] intersect(int[] nums1, int[] nums2) {
int len = nums1.length >= nums2.length ? nums1.length : nums2.length;
int[] re = new int[len];
int count = 0;
Arrays.sort(nums1);
Arrays.sort(nums2);
for (int i = 0, j = 0; i < nums1.length && j < nums2.length; ) {
if (nums1[i] == nums2[j]) {
re[count++] = nums1[i++];
j++;
}else if (nums1[i] > nums2[j]) {
j++;
}else {
i++;
}
}
int[] tem = new int[count];
for (int i = 0; i < tem.length; i++) {
tem[i] = re[i];
}
return tem;
}
public static void main(String[] args) {
int[] nums1 = new int[] { 1};
int[] nums2 = new int[] { 1 };
int[] re = intersect(nums1, nums2);
for (int i = 0; i < re.length; i++) {
System.out.print(re[i]+" ");
}
}
}