Given two arrays, write a function to compute their intersection.
Notice
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Have you met this question in a real interview?
Yes
Example
Givennums1=[1, 2, 2, 1],nums2=[2, 2], return[2, 2].
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to num2'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?
sort and merge
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
if (nums1 == null || nums2 == null) {
return null;
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0;
int index = 0;
int[] temp = new int[nums1.length];
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
temp[index++] = nums1[i];
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] ans = new int[index];
for (int k = 0; k < ans.length; k++) {
ans[k] = temp[k];
}
return ans;
}