[LeetCode] Intersection of Two Arrays II

350. Intersection of Two Arrays II

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
    • below solution is for this question.
    • if two arrays are not sorted, we can use multiset insted
  • What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
    • binary search for minimim array, if theres duplicatie numbers in nums1, we can search linear to avoid duplicate problem
    • in this case, O(nlogm) for Time, O(1) for Space
  • 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?
    • k way merge sort could be solution
    • just remeber two disk address and use as two pointer like below solution.
  • Time : O(max(nlogn + mlogm)) for sorting
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> intersect(vector<int>& n1, vector<int>& n2) {
sort(n1.begin(), n1.end());
sort(n2.begin(), n2.end());
vector<int> res;
for(int i = 0, j = 0; i < n1.size() and j < n2.size();) {
if(n1[i] == n2[j]) {
res.push_back(n1[i]);
i++; j++;
} else if(n1[i] > n2[j]) {
j++;
} else {
i++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/intersection-of-two-arrays-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.