如何在两个不同大小的向量中找到公共数字
How to find common numbers in two vectors of different sizes
我有两个不同大小的整数向量:
向量 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++;
}
}
相关文章:
- 用C++中的数字和条件填充向量
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 输入验证将数字放入向量中
- 如何在向量中某个数字之后重新计算进程
- 如何使用count_if计算向量中的可变数字范围
- 删除C++中向量中第一个最小的数字(并保持顺序)
- 如何将数字转换为整数向量?
- 如何在两个不同大小的向量中找到公共数字
- 如果我们从每个 Y 向量中选择一个值,则 X 数字的每个组合都可能
- 将向量整数拆分为这些数字的整数
- 计算向量中大于数字的元素
- Rcpp - 用二进制函数转换数字向量?
- 如何从向量转换为<char>数字整数
- 错误:数字常数之前的预期无限制ID:std :: array和std ::向量大小分配
- 在每个偶数特定数字之后,插入向量中
- 在向量中找到连续数字的更有效方法
- 如何将文件中的数字放入向量中
- 向量中出现第 N 个数字