用 C++ 找出两个已排序数组的相对补集
假设我们有两个已排序数组 arr1 和 arr2,它们的大小分别是 m 和 n。我们必须找到这两个数组的相对补集。也就是说,我们需要找出出现在 arr1 中但未出现在 arr2 中的所有元素。因此,如果数组为 A = [3, 6, 10, 12, 15],B = [1, 3, 5, 10, 16],那么结果将为 [6, 12, 15]
要解决这个问题,我们可以使用 set_difference 函数。因为该问题基本上是一个集合差操作。
示例
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int first[] = {3, 6, 10, 12, 15};
int second[] = {1, 3, 5, 10, 16};
int n = sizeof(first) / sizeof(first[0]);
vector<int> temp(5);
vector<int>::iterator it, ls;
sort(first, first + 5);
sort(second, second + 5);
cout << "First array :";
for (int i = 0; i < n; i++)
cout << " " << first[i];
cout << endl;
cout << "Second array :";
for (int i = 0; i < n; i++)
cout << " " << second[i];
cout << endl;
ls = set_difference(first, first + 5, second, second + 5, temp.begin());
cout << "The result of relative complement ";
for (it = temp.begin(); it < ls; ++it)
cout << " " << *it;
cout << endl;
}输出
First array : 3 6 10 12 15 Second array : 1 3 5 10 16 The result of relative complement 6 12 15
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP