我有一个排序的字符串向量,我试图找到向量中每个元素的共现:
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
}
}