首页 > 解决方案 > 以某种方式操作数组的值

问题描述

所以我被要求编写一个函数,以以下方式更改数组的值:

我想出了这样的事情:

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 值,它不会影响任何其他项目。有人可以帮我吗?

标签: c++arrays

解决方案


我不太遵循您的功能的逻辑,因此不能对此发表评论。

以下是我如何解释需要做的事情。请注意,我的示例实现尽可能易于理解。可能有办法让它更快。

请注意,我还使用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();
}

推荐阅读