用 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

更新於:23-Sep-2019

153 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.