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

更新於: 2019 年 12 月 23 日

2K+ 瀏覽

啟動您的 職業生涯

完成課程獲取認證

開始之前
廣告
© . All rights reserved.