如何在列表中快速搜索元素
How to quickly search for an element in a list
我有两个list<int>
(s((都排序了(
list<int> first; // length > 24 000 elements
list<int> second; // length > 3 000 000 elements
我需要获取first
列表中的所有元素,以便first
列表中的元素与second
列表中的元素在 30 以内。
例如:
first = [1,67,1111,10668]
second = [25, 90, 1000, 1004]
output:
1, 67.
我用 c++ 编写了这段代码,但是当长度超过 10 000 时second
代码很慢。
int key = 0;
for (std::list<int>::const_iterator iterator = first.begin(), end = first.end(); iterator != end; ++iterator)
{
key = *iterator;
for (int j=key;j<key+30;j++)
{
std::list<int>::iterator it = std::find(second.begin(), second.end(), j);
if ( it != second.end() )
{
//print
}
}
}
如何优化此代码以更快地搜索元素? 谢谢。
你可以以线性复杂度来做到这一点,就像std::merge
void foo(const std::list<int>& first, const std::list<int>& second, const int limit)
{
auto it1 = first.begin();
auto it2 = second.begin();
while (it1 != first.end() && it2 != second.end()) {
if (*it1 + limit < *it2) {
++it1;
} else if (*it2 + limit < *it1) {
++it2;
} else {
std::cout << *it1 << std::endl;
++it1;
}
}
}
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 高级选择排序 - 在一次迭代中搜索两个元素
- C++线性搜索算法,确定数组中元素的数量
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- C++ lower_bound() 搜索最接近目标值的元素
- 在二叉搜索树中插入新元素
- 删除二叉搜索树 (C++) 中的单个元素
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 递归搜索n元树中的元素
- 从数组中搜索元素的索引
- C++二叉搜索树实现不会添加每个元素
- 如何在列表中快速搜索元素
- 如何在使用和无发现的情况下使用和不使用的字符串向量搜索元素
- 我在哪里可以从C 中的单链接列表中创建此函数到搜索元素时犯了错误
- 将数据从文件读取到链接列表中,并在链接列表中搜索元素
- STL 容器中的搜索元素
- 如何使用队列从C++中的每个节点中搜索元素
- 插入和搜索元素最快的数据结构是什么
- 需要帮助从结构向量中搜索元素