Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return[2].
Method 1: using two set. O(N) time, O(m+n) space.
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if(nums1.size() == 0 || nums2.size() == 0) return {};
set<int> hashMap;
set<int> values;
for(int i = 0; i < nums1.size(); ++i) hashMap.insert(nums1[i]);
for(int i = 0; i < nums2.size(); ++i) {
if(hashMap.find(nums2[i]) != hashMap.end()) values.insert(nums2[i]);
}
vector<int> res;
auto iter = values.begin();
while(iter != values.end()) {
res.push_back(*iter);
iter++;
}
return res;
}
};Varations:
1: The input two arrays are sorted. The time complexity is O(m/n) whichever is larger.
// two sorted arrays interaction
vector<int> Interactions(vector<int>& a, vector<int>& b) {
if(a.size() == 0) return {};
if(b.size() == 0) return {};
int a_start = 0, b_start = 0;
vector<int> result;
while(a_start < a.size() && b_start < b.size()) {
if(a[a_start] == b[b_start]) {
result.push_back(a[a_start]);
a_start++;
b_start++;
} else if(a[a_start] < b[b_start]) a_start++;
else b_start++;
}
return result;
}2: What if one array is much longer and the other one is super short.
In this case, it is good to use binary search to search the short array's element in the super long one. Time complexity would be NLgM. M is much larger than N.
bool binarySearch(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target) return true;
else if(nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
vector<int> InteractionsII(vector<int>& longer, vector<int>& shorter) {
if(longer.size() == 0) return {};
if(shorter.size() == 0) return {};
vector<int> res;
for(int i = 0; i < shorter.size(); ++i) {
if(binarySearch(longer, shorter[i])) {
res.push_back(shorter[i]);
while(i + 1 < shorter.size() && (shorter[i] == shorter[i+1])) {
res.push_back(shorter[i]);
i++;
}
}
return res;
}
Further follow up: if two arrays are of the same length, however, the numbers are sometimes sparse, sometimes dense.
We can also apply binary search but a little tweak. Each time we search the the target, return the right border of the target.
// TODO implement
本文介绍两种数组交集的实现方法:一种使用两个哈希表,适用于任意数组;另一种针对已排序数组,采用双指针技术。同时探讨了数组长度不等及稀疏分布情况下的优化策略。
706

被折叠的 条评论
为什么被折叠?



