[英]finding a smaller number than a given number in a very large array without linear search
我想找到一個小於或等於給定數字的數字的最后一次出現。 由於整數向量非常大,因此O(n)效率不高。
我將向量分為兩部分並進行並行搜索。
讓我們以一個例子來理解:
vector <int> arr = {1, 8, 7, 1, 2, 9, 5, 7, 4 ,6};
我想找到一個小於或等於2的數字的最后一次出現,因此將數組分為兩個部分:
{1, 8, 7, 1, 2} and {9, 5, 7, 4, 6}
並從兩個數組的末尾開始搜索。
如我們所見,一個小於或等於2的數字位於位置5(索引4),但是它可能在大於5的任何位置,因此我們仍然必須完全搜索第二個數組,因為我們的目標是找到最大的元素指數。
我想問問是否有stl函數在第二個數組中找到小於2的數字,這樣我就沒有完全搜索第二個數組。
我可以使用std :: find在第二個數組中找到一個小於2的數字嗎?
編輯:小於或等於2的數字位於位置5(索引4),但是它可能在大於5的任何位置,因此我們在第一個數組中的位置5處停止,但繼續搜索第二個數組。 假設我們在位置7(索引6)處獲得元素1,因為7> 5,所以我們只返回位置7,程序結束。 這使我們不必完全搜索第一個數組。
由於我們從向量開始,因此如果從頭到尾進行搜索,則勢必會檢查每個元素。
但是,如果我們從頭到尾進行搜索,則只要滿足該謂詞,我們就可以停止。 這使得算法的最壞情況為O(N)和最佳情況為O(1)。
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
auto arr = std::vector <int>{ 1, 8, 7, 1, 2, 9, 5, 7, 4 ,6 };
auto less_than_three = [](auto&& x) { return x < 3; };
auto rpos = std::find_if(rbegin(arr), rend(arr), less_than_three);
if (rpos == rend(arr))
{
std::cout << "not found\n";
}
else
{
auto pos = prev(rpos.base());
auto index = distance(begin(arr), pos);
std::cout << "found at position " << index << "\n";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.