使所有元素在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
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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短