用 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

更新於:2019 年 12 月 17 日

364 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告