最少的删除操作,以使数组的所有元素在C ++中相同。

问题陈述

给定n个元素的数组,以便元素可以重复。我们可以从数组中删除任意数量的元素。任务是找到要从数组中删除的元素的最小数量,以使其相等。

arr[] = {10, 8, 10, 7, 10, -1, -4, 12}

我们必须删除突出显示的5个元素,以使所有数组元素相同。

算法

1. Count frequency of each element
2. Find maximum frequecy among the frequencies. Let us call this as maxFrequncy
3. Elements to be deleted: n – maxFrequecy where n is size of an array

示例

#include <iostream>
#include <unordered_map>
#include <climits>
#define SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
using namespace std;
int minDeleteOperations(int *arr, int n){
   unordered_map<int, int> frequecy;
   int maxFrequency = INT_MIN;
   for (int i = 0; i < n; ++i) {
      frequecy[arr[i]]++;
   }
   for (auto it = frequecy.begin(); it != frequecy.end(); ++it) {
      maxFrequency = max(maxFrequency, it->second);
   }
   return (n - maxFrequency);
}
int main(){
   int arr[] = {10, 8, 10, 7, 10, -1, 9, 4};
   cout << "Required deletes: " << minDeleteOperations(arr, SIZE(arr)) << "\n";
   return 0;
}

输出结果

当您编译并执行上述程序时。它生成以下输出-

Required deletes: 5