📌  相关文章
📜  最小化 Array 中的插入以使每对的比率为 K

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

最小化 Array 中的插入以使每对的比率为 K

给定一个长度为N的数组arr[] ,任务是找到要添加到数组中的最小元素数,使得数组中存在比率为K的每个独立对。

例子:

方法:上述问题可以使用贪心和散列技术解决,基于以下观察:

按照以下步骤解决上述问题:

  • 初始化一个 hashmap m 以存储数组中元素的频率。
  • 遍历数组并存储频率
  • 对数组 arr[] 进行排序。
  • 初始化 cnt_pairs 以存储配给 k 的可用对的计数。
  • 遍历排序后的数组并检查配对元素。
  • 检查比率为 k 的对是否存在于 arr[i],将它们视为一对并通过降低频率将它们从哈希图中删除。
  • 通过增加 2 来跟踪 cnt_pairs 变量中的可用对。
  • 通过从 n 中减去 cnt_pairs 来打印单个元素。

以下是上述方法的实现

C++
// C++ program to minimize insertions in
// Array to make ratio of each pair as K
 
#include 
using namespace std;
 
// Function to minimize insertions
// in Array to make ratio
// of each pair as K
int find_min_additions(
    int arr[], int n, int x)
{
    // Initialize a hashmap
    // and store the frequencies
    // of the array elements
    unordered_map m;
 
    // Traverse the array
    // and store the frequencies
    for (int i = 0; i < n; i++) {
        m[arr[i]]++;
    }
 
    // sort the array
    sort(arr, arr + n);
 
    // Initialize the cnt_pairs to store the
    // count of the available pairs
    int cnt_pairs = 0;
 
    for (int i = 0; i < n; ++i) {
 
        // Check if the pair with ratio k is
        // present for arr[i]
        if (m[arr[i] * x] > 0
            && m[arr[i]] > 0) {
 
            // Consider them as a pair
            // and remove from the hashmap
            m[arr[i] * x]--;
            m[arr[i]]--;
 
            // Add the count of the pairs
            cnt_pairs += 2;
        }
    }
 
    // Return the count of single elements
    // that need another element
    // to make ratio k
    return n - cnt_pairs;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 2, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    cout << find_min_additions(arr, n, K);
}


Java
// Java program to minimize insertions in
// Array to make ratio of each pair as K
import java.util.*;
 
class GFG{
 
  // Function to minimize insertions
  // in Array to make ratio
  // of each pair as K
  static int find_min_additions(
    int []arr, int n, int x)
  {
 
    // Initialize a hashmap
    // and store the frequencies
    // of the array elements
    HashMap m = new HashMap<>();
 
 
    // Traverse the array
    // and store the frequencies
    for (int i = 0; i < n; i++) {
      int c = 0;
      if(m.containsKey(arr[i])) {
        c = m.get(arr[i]);
      }
      m.put(arr[i], c + 1);
    }
 
    // sort the array
    Arrays.sort(arr);
 
    // Initialize the cnt_pairs to store the
    // count of the available pairs
    int cnt_pairs = 0;
 
    for (int i = 0; i < n; ++i) {
 
      // Check if the pair with ratio k is
      // present for arr[i]
      if (m.containsKey(arr[i] * x) && m.get(arr[i] * x) > 0
          && m.get(arr[i]) > 0) {
 
        // Consider them as a pair
        // and remove from the hashmap
        m.put(arr[i] * x, m.get(arr[i] * x) - 1);
        m.put(arr[i], m.get(arr[i]) - 1);
 
        // Add the count of the pairs
        cnt_pairs += 2;
      }
    }
 
    // Return the count of single elements
    // that need another element
    // to make ratio k
    return n - cnt_pairs;
  }
 
  // Driver code
  public static void main (String[] args) {
    int arr[] = { 1, 2, 2, 2, 4, 7 };
    int n = arr.length;
    int K = 2;
 
    System.out.print(find_min_additions(arr, n, K));
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3
# Python program to minimize insertions in
# Array to make ratio of each pair as K
 
# Function to minimize insertions
# in Array to make ratio
# of each pair as K
def find_min_additions(arr, n,  x):
 
    # Initialize a hashmap
    # and store the frequencies
    # of the array elements
    m = {}
 
    # Traverse the array
    # and store the frequencies
    for i in range(0, n):
        m[arr[i]] = m[arr[i]] + 1 if arr[i] in m else 1
 
    # sort the array
    arr.sort()
 
    # Initialize the cnt_pairs to store the
    # count of the available pairs
    cnt_pairs = 0
 
    for i in range(0, n):
 
        # Check if the pair with ratio k is
        # present for arr[i]
        if (arr[i] * x in m and arr[i] in m and m[arr[i] * x] > 0
                and m[arr[i]] > 0):
 
            # Consider them as a pair
            # and remove from the hashmap
            m[arr[i] * x] -= 1
            m[arr[i]] -= 1
 
            # Add the count of the pairs
            cnt_pairs += 2
 
    # Return the count of single elements
    # that need another element
    # to make ratio k
    return n - cnt_pairs
 
# Driver code
if __name__ == "__main__":
 
    arr = [1, 2, 2, 2, 4, 7]
    n = len(arr)
    K = 2
 
    print(find_min_additions(arr, n, K))
 
# This code is contributed by rakeshsahni


C#
// C# program to minimize insertions in
// Array to make ratio of each pair as K
 
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to minimize insertions
  // in Array to make ratio
  // of each pair as K
  static int find_min_additions(
    int []arr, int n, int x)
  {
 
    // Initialize a hashmap
    // and store the frequencies
    // of the array elements
    Dictionary m = 
      new Dictionary();
 
    // Traverse the array
    // and store the frequencies
    for (int i = 0; i < n; i++) {
      int c = 0;
      if(m.ContainsKey(arr[i])) {
        c = m[arr[i]];
      }
      m[arr[i]] = c + 1;
    }
 
    // sort the array
    Array.Sort(arr);
 
    // Initialize the cnt_pairs to store the
    // count of the available pairs
    int cnt_pairs = 0;
 
    for (int i = 0; i < n; ++i) {
 
      // Check if the pair with ratio k is
      // present for arr[i]
      if (m.ContainsKey(arr[i] * x) && m[arr[i] * x] > 0
          && m[arr[i]] > 0) {
 
        // Consider them as a pair
        // and remove from the hashmap
        m[arr[i] * x]--;
        m[arr[i]]--;
 
        // Add the count of the pairs
        cnt_pairs += 2;
      }
    }
 
    // Return the count of single elements
    // that need another element
    // to make ratio k
    return n - cnt_pairs;
  }
 
  // Driver code
  public static void Main()
  {
    int []arr = { 1, 2, 2, 2, 4, 7 };
    int n = arr.Length;
    int K = 2;
 
    Console.Write(find_min_additions(arr, n, K));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
2

时间复杂度: O(N*log N) 其中 N 是数组的大小。
空间复杂度: O(N)