c++ - 优化方法
问题描述
我想优化以下方法:
int getRowWithMinConflicts(int cols)
{
int minConflicts = MAX;
int rowWithMinCOnflicts[MAX];
for (int rows = 0; rows < N; rows++)
{
rowWithMinCOnflicts[rows] = getConfilictsCount(rows, cols);
int tempMin = rowWithMinCOnflicts[rows];
if (tempMin < minConflicts)
{
minConflicts = tempMin;
}
}
vector<int> currentRow;
for (int rows = 0; rows < N; rows++)
{
if (rowWithMinCOnflicts[rows] == minConflicts)
{
currentRow.push_back(rows);
}
}
return currentRow[rand() % currentRow.size()];
}
首先,我正在对 N 运行一个循环以保存数组 rowWithMinCOnflicts 值并跟踪最小值
我再次运行循环到 N 以在数组 rowWithMinCONflicts 中检查哪些条目的值 =“minConflicts”,然后我将它们添加到向量中,因为我只需要它们最后的大小。如何同时优化两个循环?
解决方案
要仅使用一个循环而不是 2 个,您可能会这样做(但我认为它不会更快):
int getRowWithMinConflicts(int cols)
{
int minConflicts = MAX;
std::vector<int> candidateRows;
for (int rows = 0; rows < N; rows++)
{
int tempMin = getConfilictsCount(rows, cols);
if (tempMin < minConflicts) {
candidateRows.clear();
candidateRows.push_back(row);
minConflicts = tempMin;
} else if (tempMin == minConflicts) {
candidateRows.push_back(row);
}
}
return currentRow[rand() % currentRow.size()];
}
还有一个没有额外内存的版本(但有额外的rand
调用):
int getRowWithMinConflicts(int cols)
{
int minConflicts = MAX;
int bestRow = -1;
std::size_t minCount = 0;
for (int rows = 0; rows < N; rows++)
{
int tempMin = getConfilictsCount(rows, cols);
if (tempMin < minConflicts) {
bestRow = row;
minCount = 1;
minConflicts = tempMin;
} else if (tempMin == minConflicts) {
++minCount;
if (rand() % minCount == 0) {
bestRow = row;
}
}
}
return bestRow;
}
推荐阅读
- c# - 如何自定义 TabbedPage 中栏的大小?[XAMARIN.FORMS]
- vue.js - 从 VueJS 中的组件获取数据
- powershell - Powershell选择不在的地方
- android - Android:自定义textView中的文本不居中
- oauth-2.0 - 如何在测试中调用 Google Account Linking?
- matlab - 任何相当于fitdist的Octave?
- com - 用新的托管 COM 可调用程序集替换 COM DLL
- javascript - queryselector 为输入字段返回不正确的值
- javascript - 赛普拉斯 - 如何在另一个请求标头中使用响应正文
- r-markdown - 我正在使用 rmarkdown::render(my_file.Rmd) 渲染 beamer_presentation 擦除了我计算机上的所有内容