用 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
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#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
广告