如何在两个不同大小的向量中找到公共数字

How to find common numbers in two vectors of different sizes

本文关键字:向量 数字 两个      更新时间:2023-10-16

我有两个不同大小的整数向量:

向量 1 = {

1, 1, 3, 3, 3, 5, 5, 8, 8, 8, 8}向量 2 = {1, 3, 3, 5, 8}

我正在尝试遍历这两个向量并比较那里的值以查看它们是否相似,然后将它们添加到新向量中。

这是我尝试过的:

vector<int> firstList{1, 1, 3, 3, 3, 5, 5, 8, 8, 8}
vector<int> secondList{1, 3, 3, 5, 8}
vector<int> finalList;
for (std::vector<char>::iterator i = firstList.begin(); i != firstList.end(); ++i)
{
if (std::find(secondList.begin(), secondList.end(), *i) != secondList.end())
{
finalList.push_back(*i);
}
}

我期望在 finalList 中的输出是:{1, 3, 3, 5, 8}

实际输出为:{1, 1, 3, 3, 3, 5, 5, 8, 8, 8, 8} 当我只需要 10 个值时,它返回 5 个值。

感谢您的任何帮助!

创建最小列表的副本,然后删除该列表上的找到的项目,以便在下一个循环中将排除找到的项目。

vector<int> firstList{1, 1, 3, 3, 3, 5, 5, 8, 8, 8}
vector<int> secondList{1, 3, 3, 5, 8}
vector<int> finalList;
vector<int> secondListCopy = secondList;
for (std::vector<int>::iterator i = firstList.begin(); i != firstList.end(); ++i)
{
std::vector<int>::iterator i2 = std::find(secondListCopy.begin(), secondListCopy.end(), *i) ;
if (i2 != secondListCopy.end())
{
finalList.push_back(*i);
secondListCopy.erase(i2);
if(secondListCopy.empty()) break; //just additional optimization.
}
}

您可以使用set.使用最大向量初始化集。

using namespace std;
int main()
{
vector<int> firstList{1, 1, 3, 3, 3, 5, 5, 8, 8, 8};
vector<int> secondList{1, 3, 3, 5, 8};
vector<int> finalList;
set<int> firstSet{firstList.begin(),firstList.end()};
for(auto& i : secondList)
if(*firstSet.find(i)) //find i in firstSet/firstList
finalList.push_back(i);

for(auto& i : finalList)
cout << i << " ";  //Output: 1 3 3 5 8 
}

在 O(NlogN( 中执行此操作的最佳方法是对两个向量进行排序并同时循环它们。

sort(firstList.begin(),firstList.end());
sort(secondList.begin(),secondList.end());
int i = 0, j = 0;
while (i < firstList.size() && j < secondList.size())
{
if (firstList[i] == secondList[j])
{
finalList.push_back(firstList[i]);
i++;j++;
}
else if (firstList[i] < secondList[j])
{
i++;
}
else
{
j++;
}
}