349. Intersection of Two Arrays
Description
Given two arrays, write a function to compute their intersection.
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note: 1.Each element in the result must be unique. 2.The result can be in any order.
Solution
- 题意即求两个数组的交集
- 我的做法并不好,如果数据范围太大就会造成溢出。
- 我的做法是用两个桶,将每个数组对应的数用0-1表示,比如nums1中有个数是6,那么num1(桶)下标为6的位置用1填充,最后两个同做与运算,从而得到交集,代码如下
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
int *rnt = (int *)malloc(sizeof(int) * (nums1Size > nums2Size ? nums1Size : nums2Size));
memset(rnt,0,sizeof(rnt));
if (nums1Size == 0 || nums2Size == 0) return rnt;
int num1[100010];
int num2[100010];
memset(num1,0,sizeof(num1));
memset(num2,0,sizeof(num2));
int max1 = nums1[0],max2 = nums2[0];
for (int i = 0;i < nums1Size;i++) {
if (nums1[i] > max1) max1 = nums1[i];
num1[nums1[i]] = 1;
}
for (int i = 0;i < nums2Size;i++) {
if (nums2[i] > max2) max2 = nums2[i];
num2[nums2[i]] = 1;
}
int MAX = max1 > max2 ? max1 : max2;
int count = 0;
for (int i = 0;i <= MAX;i++) {
if (num1[i] && num2[i]) {
rnt[count++] = i;
}
}
*returnSize = count;
return rnt;
}
- 下面给出一个set的做法,由题解给出,侵删。
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s(nums1.begin(), nums1.end());
vector<int> out;
for (int x : nums2)
if (s.erase(x))
out.push_back(x);
return out;
}