0

我有一个排序的字符串向量,我试图找到向量中每个元素的共现:

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
         }
}
4

2 回答 2

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)。与您的代码略有不同:每个单词只打印一次。

于 2013-07-25T19:52:38.117 回答
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;
于 2013-07-25T19:58:54.777 回答