使所有数组元素在C ++中相等所需的最少操作
问题陈述
给定一个具有n个正整数的数组。我们需要找到使所有元素相等的最小操作数。我们可以对数组元素上的任何元素执行加,乘,减或除运算。
示例
如果输入数组={1,2,3,4},那么我们需要最少3次操作才能使所有元素相等。例如,我们可以通过添加3个元素使元素4个。
算法
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 <bits/stdc++.h>
using namespace std;
int getMinOperations(int *arr, int n) {
unordered_map<int, int> 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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下