[LeetCode] 350. 两个数组的交集 II
给定两个数组,写一个方法来计算它们的交集。
例如:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
注意:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
跟进:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?
英文
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Java
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> res = new ArrayList<>();
for (int n : nums1) {
list.add(n);
}
for (int n : nums2) {
int i = list.indexOf(n);
if (i != -1) {
list.remove(i);
res.add(n);
}
}
int[] d = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
d[i] = res.get(i);
}
return d;
}
}
JAVA优化 2018.4.10
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] res = new int[nums1.length < nums2.length ? nums1.length : nums2.length];
int i = 0, j = 0, k = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
res[k] = nums1[i];
i++;
j++;
k++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return Arrays.copyOfRange(res, 0, k);
}
}