📌  相关文章
📜  数组中最多有 K 个不同元素所需的最少替换次数

📅  最后修改于: 2021-10-27 16:46:20             🧑  作者: Mango

给定一个由N 个正整数和一个整数K组成的数组arr[] ,任务是找到需要被其他数组元素替换的数组元素的最少数量,使得该数组最多包含K 个不同的元素。

方法:该问题可以使用贪心技术解决。这个想法是用更高频率的阵列元件替换较小频率的阵列元件。请按照以下步骤解决问题:

  • 初始化一个映射,比如mp ,以存储每个不同数组元素的频率。
  • 遍历数组并将数组中每个不同元素的频率存储到 Map 中。
  • 使用地图的键值作为i遍历地图,并将mp[i]的值插入到一个数组中,比如Freq[]
  • 按降序对数组Freq[]进行排序。
  • 初始化一个变量,比如cntMin ,以存储需要替换的数组元素的最小计数,以便数组中不同元素的计数最多为K
  • 初始化一个变量,比如len ,以存储数组Freq[]的大小。
  • 使用变量i迭代范围[K, len] 。对于每个i值,更新cntMin += Freq[i]
  • 最后,打印cntMin的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to find minimum count of array
// elements required to be replaced such that
// count of distinct elements is at most K
int min_elements(int arr[], int N, int K)
{
 
    // Store the frequency of each
    // distinct element of the array
    map mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Update frequency
        // of arr[i]
        mp[arr[i]]++;
    }
 
    // Store frequency of each distinct
    // element of the array
    vector Freq;
 
    // Traverse the map
    for (auto it : mp) {
 
        // Stores key of the map
        int i = it.first;
 
        // Insert mp[i] into Freq[]
        Freq.push_back(mp[i]);
    }
 
    // Sort Freq[] in descending order
    sort(Freq.rbegin(), Freq.rend());
 
    // Stores size of Freq[]
    int len = Freq.size();
 
    // If len is less than
    // or equal to K
    if (len <= K) {
 
        return 0;
    }
 
    // Stores minimum count of array elements
    // required to be replaced such that
    // count of distinct elements is at most K
    int cntMin = 0;
 
    // Iterate over the range [K, len]
    for (int i = K; i < len; i++) {
 
        // Update cntMin
        cntMin += Freq[i];
    }
 
    return cntMin;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int K = 3;
    cout << min_elements(arr, N, K);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
  // Function to find minimum count of array
  // elements required to be replaced such that
  // count of distinct elements is at most K
  static int min_elements(int arr[], int N, int K)
  {
 
    // Store the frequency of each
    // distinct element of the array
    HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
 
      // Update frequency
      // of arr[i]
      if(mp.containsKey(arr[i]))
      {
        mp.put(arr[i], mp.get(arr[i])+1);
      }
      else
      {
        mp.put(arr[i], 1);
      }
    }
 
    // Store frequency of each distinct
    // element of the array
    Vector Freq = new Vector();
 
    // Traverse the map
    for (Map.Entry it : mp.entrySet())
    {
 
      // Stores key of the map
      int i = it.getKey();
 
      // Insert mp[i] into Freq[]
      Freq.add(mp.get(i));
    }
 
    // Sort Freq[] in descending order
    Collections.sort(Freq,Collections.reverseOrder());
 
    // Stores size of Freq[]
    int len = Freq.size();
 
    // If len is less than
    // or equal to K
    if (len <= K)
    {
      return 0;
    }
 
    // Stores minimum count of array elements
    // required to be replaced such that
    // count of distinct elements is at most K
    int cntMin = 0;
 
    // Iterate over the range [K, len]
    for (int i = K; i < len; i++)
    {
 
      // Update cntMin
      cntMin += Freq.get(i);
    }
    return cntMin;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 };
    int N = arr.length;
    int K = 3;
    System.out.print(min_elements(arr, N, K));
  }
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program to implement
# the above approach
 
# Function to find minimum count of array
# elements required to be replaced such that
# count of distinct elements is at most K
def min_elements(arr, N, K) :
  
    # Store the frequency of each
    # distinct element of the array
    mp = {}
  
    # Traverse the array
    for i in range(N) :
  
        # Update frequency
        # of arr[i]
        if arr[i] in mp :
            mp[arr[i]] += 1
        else :
            mp[arr[i]] = 1
  
    # Store frequency of each distinct
    # element of the array
    Freq = []
  
    # Traverse the map
    for it in mp :
  
        # Stores key of the map
        i = it
  
        # Insert mp[i] into Freq[]
        Freq.append(mp[i])
  
    # Sort Freq[] in descending order
    Freq.sort()
    Freq.reverse()
  
    # Stores size of Freq[]
    Len = len(Freq)
  
    # If len is less than
    # or equal to K
    if (Len <= K) :
        return 0
  
    # Stores minimum count of array elements
    # required to be replaced such that
    # count of distinct elements is at most K
    cntMin = 0
  
    # Iterate over the range [K, len]
    for i in range(K, Len) :
  
        # Update cntMin
        cntMin += Freq[i]
  
    return cntMin
     
  # Driver code
arr = [ 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 ]
N = len(arr)
K = 3;
print(min_elements(arr, N, K))
 
# This code is contributed by divyesh072019.


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find minimum count of array
// elements required to be replaced such that
// count of distinct elements is at most K
static int min_elements(int []arr, int N, int K)
{
     
    // Store the frequency of each
    // distinct element of the array
    Dictionary mp = new Dictionary();
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency
        // of arr[i]
        if (mp.ContainsKey(arr[i]))
        {
            mp[arr[i]] = mp[arr[i]] + 1;
        }
        else
        {
            mp.Add(arr[i], 1);
        }
    }
     
    // Store frequency of each distinct
    // element of the array
    List Freq = new List();
     
    // Traverse the map
    foreach (KeyValuePair it in mp)
    {
         
        // Stores key of the map
        int i = it.Key;
         
        // Insert mp[i] into Freq[]
        Freq.Add(mp[i]);
    }
     
    // Sort Freq[] in descending order
    Freq.Sort();
    Freq.Reverse();
     
    // Stores size of Freq[]
    int len = Freq.Count;
     
    // If len is less than
    // or equal to K
    if (len <= K)
    {
        return 0;
    }
     
    // Stores minimum count of array elements
    // required to be replaced such that
    // count of distinct elements is at most K
    int cntMin = 0;
     
    // Iterate over the range [K, len]
    for(int i = K; i < len; i++)
    {
         
        // Update cntMin
        cntMin += Freq[i];
    }
    return cntMin;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 };
    int N = arr.Length;
    int K = 3;
     
    Console.Write(min_elements(arr, N, K));
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
3

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程