c++ - 以某种方式操作数组的值
问题描述
所以我被要求编写一个函数,以以下方式更改数组的值:
- 所有最小的值都不会改变
- 如果,让我们假设,最小的数字是 2 并且没有 3 和 4,那么所有 5 都被更改为 3 等等。
- 例如,对于数组 = [2, 5, 7, 5],我们将得到 [2, 3, 4, 3],它概括为获得保持不变的数组的最小值,以及每隔一个最小值(不包括第一个)根据最小值进行更改。在我们的例子中 - 5 是第一个最小值(除了 2),所以它是 2(第一个最小值)+ 1 = 3,7 是 2 之后的第二个最小值,所以它是 2+2(因为它是第二个最小值)。
我想出了这样的事情:
int fillGaps(int arr[], size_t sz){
int min = *min_element(arr, arr+sz);
int w = 1;
for (int i = 0; i<sz; i++){
if (arr[i] == min) {continue;}
else{
int mini = *min_element(arr+i, arr+sz);
for (int j = 0; j<sz; j++){
if (arr[j] == mini){arr[j] = min+w;}
}
w++;}
}
return arr[sz-1];
}
但是它仅适用于第 0 和第 1 值,它不会影响任何其他项目。有人可以帮我吗?
解决方案
我不太遵循您的功能的逻辑,因此不能对此发表评论。
以下是我如何解释需要做的事情。请注意,我的示例实现尽可能易于理解。可能有办法让它更快。
请注意,我还使用std::vector
, 来使内容更具可读性和 C++ 风格。你真的不应该传递原始指针和大小,这很容易出错。至少将它们捆绑在一个结构中。
#include <algorithm>
#include <set>
#include <unordered_map>
#include <vector>
int fillGaps (std::vector<int> & data) {
// Make sure we don't have to worry about edge cases in the code below.
if (data.empty()) { return 0; }
/* The minimum number of times we need to loop over the data is two.
* First to check which values are in there, which lets us decide
* what each original value should be replaced with. Second to do the
* actual replacing.
*
* So let's trade some memory for speed and start by creating a lookup table.
* Each entry will map an existing value to its new value. Let's use the
* "define lambda and immediately invoke it" to make the scope of variables
* used to calculate all this as small as possible.
*/
auto const valueMapping = [&data] {
// Use an std::set so we get all unique values in sorted order.
std::set<int> values;
for (int e : data) { values.insert(e); }
std::unordered_map<int, int> result;
result.reserve(values.size());
// Map minimum value to itself, and increase replacement value by one for
// each subsequent value present in the data vector.
int replacement = *values.begin();
for (auto e : values) { result.emplace(e, replacement++); }
return result;
}();
// Now the actual algorithm is trivial: loop over the data and replace each
// element with its replacement value.
for (auto & e : data) { e = valueMapping.at(e); }
return data.back();
}
推荐阅读
- dropzone.js - 为什么 dropzoneJS 调整大小选项没有影响?
- javascript - yeoman-test 找不到子生成器
- angular - 离子角度下拉列表
- r - 在 R 中填充矩阵的更快方法
- mysql - 如何在 laravel 或 sql 中使用 like 选择数据而不考虑后字符
- python - `Layer.call` 的第一个参数必须始终传递
- python - 使用默认样式时,无法访问 MS-Word 文件中样式的属性,使用 python-docx
- android - Android - Recyclerview 内的 VideoView 匹配父宽度并保持纵横比
- android - 加载 InterstitialAd 时 Flutter App 崩溃
- math - 函数的意外乘法结果