我有一个排序的字符串向量,我试图找到向量中每个元素的共存:
V = {“AAA”,“AAA”,“AAA”,“BCA”,...}
int main()
{
vector<string> vec;
//for every word in the vector
for(size_t i = 0; i < vec.size();i++)
{
int counter = 0;
//loop through the vector and count the coocurrence of this word
for(size_t j = 0; j < vec.size();j++)
{
if(vec[i] == vec[j]) counter +=1;
}
cout << vec[i] << " "<<counter <<ed,l
}
}
复杂性是O(n ^ 2)对吗?我花了这么多时间才能找到解决问题的方法?
谢谢,
这就是编辑:
int main()
{
vector<string> vec;
//for every word in the vector
for(size_t i = 0; i < vec.size();i++)
{
int counter = 0;
//loop through the vector and count the coocurrence of this word
for(size_t j = i+1; j < vec.size()-1;j++)
{
if(vec[i] == vec[j]) counter +=1;
}
cout << vec[i] << " "<<counter <<ed,l
}
}
答案 0 :(得分:8)
未经测试。我假设向量包含至少一个元素。
counter = 1
for(size_t i = 1; i < vec.size(); i++)
{
if(vec[i] == vec[i-1]) counter +=1;
else
{
std::cout << vec[i-1] << ", " << counter << std::endl;
counter = 1;
}
}
std::cout << vec[i-1] << ", " << counter << std::endl;
这显然是O(n)。与您的代码略有不同:每个单词只打印一次。
答案 1 :(得分:3)
经过测试,O(n),即使矢量未被排序或者它是空的,也能正常工作:
#include <iostream>
#include <vector>
#include <unordered_map>
int main()
{
std::vector<std::string> v = { "aaa", "abc", "aaa", "def", "aaa", "aaa", "abc", "ghi" };
std::unordered_map<std::string, int> m;
for (std::vector<std::string>::iterator it = v.begin(); it != v.end(); it++)
m[*it]++;
for (std::unordered_map<std::string, int>::iterator it = m.begin(); it != m.end(); it++)
std::cout << it->first << " -> " << it->second << std::endl;
return 0;
}
或者,为了便于阅读,使用基于范围的循环重写了相应的片段(感谢Frerich Raabe):
for (const auto it: v)
m[it]++;
for (const auto it: m)
std::cout << it.first << " -> " << it.second << std::endl;