📌  相关文章
📜  使所有剩余数组元素的频率相等所需的最小移除

📅  最后修改于: 2021-09-07 02:33:38             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是找到需要删除的最小数组元素数,以使剩余数组元素的频率变得相等。

例子 :

朴素的方法:我们计算数组中每个元素的频率。然后对于频率图中的每个值v ,我们遍历频率图并检查此当前值是否小于v ,如果为真,则将此当前值添加到我们的结果中,如果为假,则添加两者之间的差异当前值和v到我们的结果。每次遍历后,存储当前结果和先前结果的最小值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to get minimum removals required
// to make frequency of all remaining elements equal
int minDelete(int arr[], int n)
{
    // Create an hash map and store frequencies of all
    // array elements in it using element as key and
    // frequency as value
    unordered_map freq;
    for (int i = 0; i < n; i++)
        freq[arr[i]]++;
 
    // Initialize the result to store the minimum deletions
    int tempans, res = INT_MAX;
 
    // Find deletions required for each element and store
    // the minimum deletions in result
    for (auto itr = freq.begin(); itr != freq.end();
         itr++) {
        tempans = 0;
        for (auto j = freq.begin(); j != freq.end(); j++) {
            if (j->second < itr->second) {
                tempans = tempans + j->second;
            }
            else {
                tempans
                    = tempans + (j->second - itr->second);
            }
        }
        res = min(res, tempans);
    }
 
    return res;
}
 
// Driver program to run the case
int main()
{
    int arr[] = {2, 4, 3, 2, 5, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << minDelete(arr, n);
    return 0;
}


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the minimum
// removals required to make frequency
// of all array elements equal
int minDeletions(int arr[], int N)
{
    // Stores frequency of
    // all array elements
    map freq;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
        freq[arr[i]]++;
    }
 
    // Stores all the frequencies
    vector v;
 
    // Traverse the map
    for (auto z : freq) {
        v.push_back(z.second);
    }
 
    // Sort the frequencies
    sort(v.begin(), v.end());
 
    // Count of frequencies
    int size = v.size();
 
    // Stores the final count
    int ans = N - (v[0] * size);
 
    // Traverse the vector
    for (int i = 1; i < v.size(); i++) {
 
        // Count the number of removals
        // for each frequency and update
        // the minimum removals required
        if (v[i] != v[i - 1]) {
            int safe = v[i] * (size - i);
            ans = min(ans, N - safe);
        }
    }
 
    // Print the final count
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 3, 2, 5, 3 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call to print the minimum
    // number of removals required
    minDeletions(arr, N);
}


Java
/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
 
class GFG {
  public static void minDeletions(int arr[], int N)
  {
     
    // Stores frequency of
    // all array elements
    HashMap map = new HashMap<>();
    ;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
      Integer k = map.get(arr[i]);
      map.put(arr[i], (k == null) ? 1 : k + 1);
    }
 
    // Stores all the frequencies
    ArrayList v = new ArrayList<>();
 
    // Traverse the map
    for (Map.Entry e :
         map.entrySet()) {
      v.add(e.getValue());
    }
 
    // Sort the frequencies
    Collections.sort(v);
 
    // Count of frequencies
    int size = v.size();
 
    // Stores the final count
    int ans = N - (v.get(0) * size);
 
    // Traverse the vector
    for (int i = 1; i < v.size(); i++) {
 
      // Count the number of removals
      // for each frequency and update
      // the minimum removals required
      if (v.get(i) != v.get(i - 1)) {
        int safe = v.get(i) * (size - i);
        ans = Math.min(ans, N - safe);
      }
    }
 
    // Print the final count
    System.out.println(ans);
  }
 
  // Driver code
  public static void main(String[] args)
  {
     
    // Given array
    int arr[] = { 2, 4, 3, 2, 5, 3 };
 
    // Size of the array
    int N = 6;
 
    // Function call to print the minimum
    // number of removals required
    minDeletions(arr, N);
  }
}
 
// This code is contributed by aditya7409.


Python3
# Python 3 program for the above approach
from collections import defaultdict
 
# Function to count the minimum
# removals required to make frequency
# of all array elements equal
def minDeletions(arr, N):
   
    # Stores frequency of
    # all array elements
    freq = defaultdict(int)
 
    # Traverse the array
    for i in range(N):
        freq[arr[i]] += 1
 
    # Stores all the frequencies
    v = []
 
    # Traverse the map
    for z in freq.keys():
        v.append(freq[z])
 
    # Sort the frequencies
    v.sort()
 
    # Count of frequencies
    size = len(v)
 
    # Stores the final count
    ans = N - (v[0] * size)
 
    # Traverse the vector
    for i in range(1, len(v)):
 
        # Count the number of removals
        # for each frequency and update
        # the minimum removals required
        if (v[i] != v[i - 1]):
            safe = v[i] * (size - i)
            ans = min(ans, N - safe)
 
    # Print the final count
    print(ans)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given array
    arr = [2, 4, 3, 2, 5, 3]
 
    # Size of the array
    N = len(arr)
 
    # Function call to print the minimum
    # number of removals required
    minDeletions(arr, N)
 
    # This code is contributed by chitranayal.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
  // Function to count the minimum
  // removals required to make frequency
  // of all array elements equal
  static void minDeletions(int []arr, int N)
  {
 
    // Stores frequency of
    // all array elements
    Dictionary freq = new Dictionary();
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
      if(freq.ContainsKey(arr[i]))
        freq[arr[i]]++;
      else
        freq[arr[i]] = 1;
    }
 
    // Stores all the frequencies
    List v = new List();
 
    // Traverse the map
    foreach (var z in freq) {
      v.Add(z.Value);
    }
 
    // Sort the frequencies
    int sz = v.Count;
    int []temp = new int[sz];
    for(int i = 0; i < v.Count; i++)
      temp[i] = v[i];
    Array.Sort(temp);
    for(int i = 0; i < v.Count; i++)
      v[i] = temp[i];
 
    // Count of frequencies
    int size = v.Count;
 
    // Stores the final count
    int ans = N - (v[0] * size);
 
    // Traverse the vector
    for (int i = 1; i < v.Count; i++) {
 
      // Count the number of removals
      // for each frequency and update
      // the minimum removals required
      if (v[i] != v[i - 1]) {
        int safe = v[i] * (size - i);
        ans = Math.Min(ans, N - safe);
      }
    }
 
    // Print the final count
    Console.WriteLine(ans);
  }
 
  // Driver Code
  public static void Main()
  {
 
    // Given array
    int []arr = { 2, 4, 3, 2, 5, 3 };
 
    // Size of the array
    int N = arr.Length;
 
    // Function call to print the minimum
    // number of removals required
    minDeletions(arr, N);
  }
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript


输出
2

有效方法:按照以下步骤解决问题:

  • 初始化一个有序映射,比如freq,以存储所有数组元素的频率。
  • 遍历数组arr[] ,存储数组元素各自的频率。
  • 初始化一个向量,比如v,以存储地图中存储的所有频率。
  • 对向量v 进行排序
  • 初始化一个变量,比如ans,来存储最终的计数。
  • 遍历向量v并对每个频率,计算需要移除的元素数量,以使剩余元素的频率相等。
  • 打印获得的所有移除计数中的最小值。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the minimum
// removals required to make frequency
// of all array elements equal
int minDeletions(int arr[], int N)
{
    // Stores frequency of
    // all array elements
    map freq;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
        freq[arr[i]]++;
    }
 
    // Stores all the frequencies
    vector v;
 
    // Traverse the map
    for (auto z : freq) {
        v.push_back(z.second);
    }
 
    // Sort the frequencies
    sort(v.begin(), v.end());
 
    // Count of frequencies
    int size = v.size();
 
    // Stores the final count
    int ans = N - (v[0] * size);
 
    // Traverse the vector
    for (int i = 1; i < v.size(); i++) {
 
        // Count the number of removals
        // for each frequency and update
        // the minimum removals required
        if (v[i] != v[i - 1]) {
            int safe = v[i] * (size - i);
            ans = min(ans, N - safe);
        }
    }
 
    // Print the final count
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 3, 2, 5, 3 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call to print the minimum
    // number of removals required
    minDeletions(arr, N);
}

Java

/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
 
class GFG {
  public static void minDeletions(int arr[], int N)
  {
     
    // Stores frequency of
    // all array elements
    HashMap map = new HashMap<>();
    ;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
      Integer k = map.get(arr[i]);
      map.put(arr[i], (k == null) ? 1 : k + 1);
    }
 
    // Stores all the frequencies
    ArrayList v = new ArrayList<>();
 
    // Traverse the map
    for (Map.Entry e :
         map.entrySet()) {
      v.add(e.getValue());
    }
 
    // Sort the frequencies
    Collections.sort(v);
 
    // Count of frequencies
    int size = v.size();
 
    // Stores the final count
    int ans = N - (v.get(0) * size);
 
    // Traverse the vector
    for (int i = 1; i < v.size(); i++) {
 
      // Count the number of removals
      // for each frequency and update
      // the minimum removals required
      if (v.get(i) != v.get(i - 1)) {
        int safe = v.get(i) * (size - i);
        ans = Math.min(ans, N - safe);
      }
    }
 
    // Print the final count
    System.out.println(ans);
  }
 
  // Driver code
  public static void main(String[] args)
  {
     
    // Given array
    int arr[] = { 2, 4, 3, 2, 5, 3 };
 
    // Size of the array
    int N = 6;
 
    // Function call to print the minimum
    // number of removals required
    minDeletions(arr, N);
  }
}
 
// This code is contributed by aditya7409.

蟒蛇3

# Python 3 program for the above approach
from collections import defaultdict
 
# Function to count the minimum
# removals required to make frequency
# of all array elements equal
def minDeletions(arr, N):
   
    # Stores frequency of
    # all array elements
    freq = defaultdict(int)
 
    # Traverse the array
    for i in range(N):
        freq[arr[i]] += 1
 
    # Stores all the frequencies
    v = []
 
    # Traverse the map
    for z in freq.keys():
        v.append(freq[z])
 
    # Sort the frequencies
    v.sort()
 
    # Count of frequencies
    size = len(v)
 
    # Stores the final count
    ans = N - (v[0] * size)
 
    # Traverse the vector
    for i in range(1, len(v)):
 
        # Count the number of removals
        # for each frequency and update
        # the minimum removals required
        if (v[i] != v[i - 1]):
            safe = v[i] * (size - i)
            ans = min(ans, N - safe)
 
    # Print the final count
    print(ans)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given array
    arr = [2, 4, 3, 2, 5, 3]
 
    # Size of the array
    N = len(arr)
 
    # Function call to print the minimum
    # number of removals required
    minDeletions(arr, N)
 
    # This code is contributed by chitranayal.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
  // Function to count the minimum
  // removals required to make frequency
  // of all array elements equal
  static void minDeletions(int []arr, int N)
  {
 
    // Stores frequency of
    // all array elements
    Dictionary freq = new Dictionary();
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
      if(freq.ContainsKey(arr[i]))
        freq[arr[i]]++;
      else
        freq[arr[i]] = 1;
    }
 
    // Stores all the frequencies
    List v = new List();
 
    // Traverse the map
    foreach (var z in freq) {
      v.Add(z.Value);
    }
 
    // Sort the frequencies
    int sz = v.Count;
    int []temp = new int[sz];
    for(int i = 0; i < v.Count; i++)
      temp[i] = v[i];
    Array.Sort(temp);
    for(int i = 0; i < v.Count; i++)
      v[i] = temp[i];
 
    // Count of frequencies
    int size = v.Count;
 
    // Stores the final count
    int ans = N - (v[0] * size);
 
    // Traverse the vector
    for (int i = 1; i < v.Count; i++) {
 
      // Count the number of removals
      // for each frequency and update
      // the minimum removals required
      if (v[i] != v[i - 1]) {
        int safe = v[i] * (size - i);
        ans = Math.Min(ans, N - safe);
      }
    }
 
    // Print the final count
    Console.WriteLine(ans);
  }
 
  // Driver Code
  public static void Main()
  {
 
    // Given array
    int []arr = { 2, 4, 3, 2, 5, 3 };
 
    // Size of the array
    int N = arr.Length;
 
    // Function call to print the minimum
    // number of removals required
    minDeletions(arr, N);
  }
}
 
// This code is contributed by SURENDRA_GANGWAR.

Javascript


输出
2

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live