Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

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