如何减少执行时间?

发布于 2025-01-17 02:12:25 字数 650 浏览 3 评论 0原文

这是一个函数的代码片段,该函数采用字符串向量(客户姓名向量)并需要查找以某种频率出现的名称。如何让它运行得更快(快于 2 秒,尤其是处理较大的数据集时)。该函数是程序的所有功能。

提前致谢。

vector<string> most_active(vector<string> &customers) {
    vector<string> result;
    double p = (double)customers.size()*5/100;
    
    for(string &customer: customers) {
        if(find(result.begin(), result.end(), customer) != result.end())
            continue;
        if(count(customers.begin(), customers.end(), customer) >= p)
                result.push_back(customer);
    }

    sort(result.begin(), result.end());

    return result;
}

我尝试通过引用传递数据而不是通过值传递数据,但这没有帮助

Here is a code snippet of a function that takes vector of strings (vector of customer names) and need to find names which occurs with some frequency. How to make it run faster (faster than 2 seconds especially operating with larger sets of data). This function is the all functionality of a program.

Thanks in advance.

vector<string> most_active(vector<string> &customers) {
    vector<string> result;
    double p = (double)customers.size()*5/100;
    
    for(string &customer: customers) {
        if(find(result.begin(), result.end(), customer) != result.end())
            continue;
        if(count(customers.begin(), customers.end(), customer) >= p)
                result.push_back(customer);
    }

    sort(result.begin(), result.end());

    return result;
}

I tried to pass data by reference instead of passing by value, but it didn't help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魔法少女 2025-01-24 02:12:25

看起来 result 应该是 std::set 因为您希望保持数据有序并且不希望有任何重复项。这需要您的 O(n²) 算法并使其成为 O(n log(n))

set<string> most_active(vector<string>& customers) {
  set<string> result;
  double p = (double)customers.size() * 5 / 100;

  for (string const& customer : customers) {
    if (customer.size() >= p)
      result.insert(customer);
  }
  return result;
}

It looks like result should be a std::set since you want to keep the data ordered and you don't want any duplicates. This takes your O(n²) algorithm and makes it O(n log(n)).

set<string> most_active(vector<string>& customers) {
  set<string> result;
  double p = (double)customers.size() * 5 / 100;

  for (string const& customer : customers) {
    if (customer.size() >= p)
      result.insert(customer);
  }
  return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文