C++ 中使数组中所有元素相等的最小操作数


问题描述

给定包含 n 个正整数的数组。我们需要找出使数组中所有元素相等的最小操作次数。我们可以对数组中任意元素执行加法、乘法、减法或除法操作。

示例

如果输入数组为 = {1, 2, 3, 4},那么我们需要最小 3 次操作才能使所有元素相等。例如,我们可以通过进行 3 次加法操作将元素变为 4。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

算法

1. Select element with maximum frequency. Let us call it ‘x’
2. Now we have to perform n-x operations as there are x element with same value

示例

 在线演示

#include
using namespace std;
int getMinOperations(int *arr, int n) {
   unordered_map hash;
   for (int i = 0;i < n; ++i) {
      hash[arr[i]]++;
   }
   int maxFrequency = 0;
   for (auto elem : hash) {
      if (elem.second > maxFrequency) {
         maxFrequency = elem.second;
      }
   }
   return (n - maxFrequency);
}
int main() {
   int arr[] = {1, 2, 3, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum required operations = " <<
   getMinOperations(arr, n) << endl;
   return 0;
}

当你编译和执行上述程序时,它会生成以下输出

输出

Minimum required operations = 3

更新于: 2019 年 12 月 23 日

2K+ 浏览

启动您的 职业生涯

完成课程获取认证

开始之前
广告