如何在列表中快速搜索元素

How to quickly search for an element in a list

本文关键字:搜索 元素 列表      更新时间:2023-10-16

我有两个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;
}
}
}