C++ 中两个列表中共同元素的最小索引和
假设两个人想选择不同的城市,他们以不同的列表列出了这些城市,我们需要帮助他们找到共同的选择。因此,我们需要找到他们都标记的那些城市。
此操作与集合交集特性非常相似,我们将两个列表作为集合,然后执行集合交集以获取公共元素。
实例
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<string> commonInterest(string set1[], int n1, string set2[], int n2) { vector<string> v(min(n1, n2)); vector<string>::iterator it; // Sorting both the list sort(set1, set1 + n1); sort(set2, set2 + n2); it = set_intersection(set1, set1 + n1, set2, set2 + n2, v.begin()); return v; } int main() { string first[] = { "Kolkata", "Hyderabad", "Chennai", "Delhi" }; int n1 = sizeof(first) / sizeof(first[0]); string second[] = { "Mumbai", "Kolkata", "Durgapur", "Delhi" }; int n2 = sizeof(second) / sizeof(second[0]); vector<string> v = commonInterest(first, n1, second, n2); cout << "Common cities: "; for (int i = 0; i < v.size(); i++) cout << ' ' << v[i]; cout << endl; }
输出
Common cities: Delhi Kolkata
广告