📌  相关文章
📜  最小化插入或删除以使每个数组元素的频率等于其值

📅  最后修改于: 2022-05-13 01:56:09.042000             🧑  作者: Mango

最小化插入或删除以使每个数组元素的频率等于其值

给定一个包含N个整数的数组arr[] ,任务是找到使每个元素的频率等于其值所需的最小插入或删除操作。

例子:

方法:给定的问题可以使用贪心方法来解决。请按照以下步骤解决给定的问题:

  • 创建一个哈希映射freq ,用于存储数组中所有元素的频率。
  • 使用变量key遍历地图的所有值。如果freq[key] > key ,它会将(freq[key] – key)贡献到总操作数中,否则,它将min(freq[key], key – freq[key])贡献到总操作数中。
  • 创建一个变量计数,它存储所有可能的键值的操作计数,这将是所需的答案。

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
#include 
using namespace std;
 
// Function to find minimum insertions or
// deletions required to make frequency
// of each element equal to its value
int minOperations(int arr[], int n)
{
   
    // Initializing Hash Map for making
    // frequency map
    map mp;
 
    // Making frequency map
    for (int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }
 
    // Stores the final count of operations
    int count = 0;
 
    // Traversing Hash Map
    for (auto it : mp) {
 
        // Updating the operation count
        if (it.second >= it.first)
            count += (it.second - it.first);
        else
            count += min(it.first - it.second, it.second);
    }
 
    // Return Answer
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 3, 4, 3, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int count = minOperations(arr, n);
    cout << count;
    return 0;
}
 
// This code is contributed by kdheraj.


Java
// Java implementation of the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find minimum insertions or
    // deletions required to make frequency
    // of each element equal to its value
    public static int minOperations(int[] arr, int n)
    {
        // Initializing Hash Map for making
        // frequency map
        Map freq = new HashMap<>();
 
        // Making frequency map
        for (int val : arr)
            freq.put(val, freq.getOrDefault(val, 0) + 1);
 
        // Stores the final count of operations
        int count = 0;
 
        // Traversing Hash Map
        for (Map.Entry mp : freq.entrySet()) {
 
            int key = (int)mp.getKey();
            int val = (int)mp.getValue();
 
            // Updating the operation count
            if (val >= key)
                count += val - key;
            else
                count += Math.min(key - val, val);
        }
 
        // Return Answer
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 3, 3, 4, 3, 1, 2 };
        int n = arr.length;
        System.out.println(minOperations(arr, n));
    }
}


Python3
# Python 3 implementation of above approach
from collections import defaultdict
 
# Function to find minimum insertions or
# deletions required to make frequency
# of each element equal to its value
def minOperations(arr, n):
 
    # Initializing Hash Map for making
    # frequency map
    mp = defaultdict(int)
 
    # Making frequency map
    for i in range(n):
        mp[arr[i]] += 1
 
    # Stores the final count of operations
    count = 0
 
    # Traversing Hash Map
    for it in mp:
 
        # Updating the operation count
        if (mp[it] >= it):
            count += (mp[it] - it)
 
        else:
            count += min(it - mp[it], mp[it])
 
    # Return Answer
    return count
 
# Driver Code
if __name__ == "__main__":
 
    arr = [3, 3, 4, 3, 1, 2]
    n = len(arr)
    count = minOperations(arr, n)
    print(count)
 
    # This code is contributed by ukasp.


C#
// C# implementation of the above approach
 
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG {
 
// Function to find minimum insertions or
// deletions required to make frequency
// of each element equal to its value
static int minOperations(int []arr, int n)
{
   
    // Initializing Hash Map for making
    // frequency map
    Dictionary mp =
          new Dictionary();
  
 
    // Making frequency map
    for (int i = 0; i < n; i++) {
        if (mp.ContainsKey(arr[i])) {
              int val = mp[arr[i]];
              mp.Remove(arr[i]);
              mp.Add(arr[i], val + 1);
        }
        else {
          mp.Add(arr[i], 1);
        }
    }
 
    // Stores the final count of operations
    int count = 0;
 
    // Traversing Hash Map
    foreach(KeyValuePair it in mp) {
 
        // Updating the operation count
        if (it.Value >= it.Key)
            count += (it.Value - it.Key);
        else
            count += Math.Min(it.Key - it.Value, it.Value);
    }
 
    // Return Answer
    return count;
}
 
 
// Driver code
public static void Main()
{
    int[] arr = { 3, 3, 4, 3, 1, 2 };
    int n = arr.Length;
    Console.Write(minOperations(arr, n));
}
}
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
2

时间复杂度: O(N)
辅助空间: O(N)