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?
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?
Subscribe to see which companies asked this question.
题目大意:找出两个集合的交集;
解题思路:先将两个集合排序,找出较小的那个集合,较小集合中的每个元素到较大的集合中去寻找有没有相等的值,如果有的话,就把该元素压入的新的容器中,并将该元素从较大的集合中删除,在大集合中查找元素时可以使用二分法查找。具体代码如下:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> re;
if (nums1.size() == 0 || nums2.size() == 0)
return re;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int>::iterator it;
if (nums1.size() >= nums2.size())
{
for (int i = 0; i < nums2.size(); i++)//少一个循环
{ int left = 0;
int right = nums1.size() - 1;
while (left <=right)
{
int mid = (right - left) / 2 + left;
if (nums2[i] == nums1[mid])
{
re.push_back(nums2[i]);
it = nums1.begin() + mid;
nums1.erase(it);
break;
}
else if (nums2[i] > nums1[mid])
left = mid + 1;
else
right = mid - 1;
}
}
return re;
}
else if (nums1.size()<nums2.size())
{
for (int i = 0; i < nums1.size(); i++)
{
int left = 0;
int right = nums2.size() - 1;
while (left <= right)
{
int mid = (right - left) / 2 + left;
if (nums1[i] == nums2[mid])
{
re.push_back(nums1[i]);
it = nums2.begin() + mid;
nums2.erase(it);
break;
}
else if (nums1[i] > nums2[mid])
left = mid + 1;
else
right = mid - 1;
}
}
return re;
}
}
};
本文介绍了一种求解两个整数数组交集的算法实现,通过先对数组进行排序,然后选择较短的数组遍历查找较长数组中的匹配项,并采用二分查找法优化搜索过程。
898

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



