用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP