在多个同时矢量迭代中,复杂性降低至O(n)
Complexity Reduction to O(n) Over Multiple Simultaeneous Vector Iteration
所以我有2个字符串向量,其中包含以下内容:
tokens: name name place thing thing
u_tokens: name place thing
现在,我的任务是同时循环浏览这两个向量,并找到每个单词的出现并将其存储在第三个向量中。这是我所做的最小工作实现(我的任务没有提及重复项,因此我不考虑删除它):
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> counts;
vector<string> tokens;
vector<string> u_tokens;
tokens.push_back("name");
tokens.push_back("name");
tokens.push_back("place");
tokens.push_back("thing");
tokens.push_back("thing");
u_tokens.push_back("name");
u_tokens.push_back("place");
u_tokens.push_back("thing");
string temp;
int temp_count = 0;
for (int i = 0; i < tokens.size(); i++)
{
temp = tokens[i];
for (int j = 0; j < u_tokens.size(); j++)
{
if(temp == u_tokens[j])
{
temp_count++;
}
}
temp = tokens[i];
for (int k = 0; k < tokens.size(); k++)
{
if (temp == tokens[k])
{
temp_count++;
}
}
counts.push_back(temp_count);
temp_count = 0;
}
for (vector<int>::const_iterator i = counts.begin(); i != counts.end(); ++i)
cout << *i << " ";
return 0;
}
但是,我注意到,这显然具有O(n^2)
的复杂性。如何将其简化为O(n)
?有可能吗?
问候。
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
void CountOccurences(const vector<string>& input, unordered_map<string, size_t>& occurences)
{
for (int i = 0; i < input.size(); i++)
{
occurences[input[i]]++;
}
}
int main()
{
vector<string> tokens;
vector<string> u_tokens;
unordered_map<string, size_t> occurences;
tokens.push_back("name");
tokens.push_back("name");
tokens.push_back("place");
tokens.push_back("thing");
tokens.push_back("thing");
u_tokens.push_back("name");
u_tokens.push_back("place");
u_tokens.push_back("thing");
CountOccurences(tokens, occurences);
CountOccurences(u_tokens, occurences);
for (auto i : occurences)
cout << i.first << "=" << i.second << " ";
return 0;
}
使用std::unordered_map
作为O(1)访问容器来创建O(n)解决方案。当然,记忆成本。
链接到在线编译程序
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 在向量内的向量上迭代
- std::unordered_set迭代器遍历的复杂性
- 在多个同时矢量迭代中,复杂性降低至O(n)
- 二进制搜索树中按顺序遍历的复杂性(使用迭代器)
- 如何提高哈希图迭代的复杂性
- map/set :: 插入是否提供了正确的迭代器提示,它的复杂性是多少?
- 为什么c++标准需要std::分区来满足不同类型迭代器的不同复杂性