📌  相关文章
📜  使所有数组元素相等所需的除法计数最小化 2

📅  最后修改于: 2021-10-27 07:09:56             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,任务是找到数组元素除以2的最小除数(整数除法),以使所有数组元素相同。

例子:

方法:解决给定问题的想法是找到数组中所有元素可以减少到的最大数量。请按照以下步骤解决问题:

  • 初始化一个变量,比如ans ,以存储所需的除法运算的最小计数。
  • 初始化一个 HashMap,比如M ,以存储数组元素的频率。
  • 遍历数组arr[]直到发现任何数组元素arr[i]大于0 。继续将arr[i]除以2并同时更新 Map M 中获得的元素的频率。
  • 遍历 HashMap 并找到频率为N的最大元素。将其存储在maxNumber 中
  • 再次遍历数组arr[]并通过将arr[i]除以2并将操作计数添加到变量ans 中,找到将arr[i]减少到maxNumber所需的操作数。
  • 完成以上步骤后,打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count minimum number of
// division by 2 operations required to
// make all array elements equal
void makeArrayEqual(int A[], int n)
{
    // Stores the frequencies of elements
    map mp;
 
    // Stores the maximum number to
    // which every array element
    // can be reduced to
    int max_number = 0;
 
    // Stores the minimum number
    // of operations required
    int ans = 0;
 
    // Traverse the array and store
    // the frequencies in the map
    for (int i = 0; i < n; i++) {
 
        int b = A[i];
 
        // Iterate while b > 0
        while (b) {
            mp[b]++;
 
            // Keep dividing b by 2
            b /= 2;
        }
    }
 
    // Iterate over the map to find
    // the required maximum number
    for (auto x : mp) {
 
        // Check if the frequency
        // is equal to n
        if (x.second == n) {
 
            // If true, store it in
            // max_number
            max_number = x.first;
        }
    }
 
    // Iterate over the array, A[]
    for (int i = 0; i < n; i++) {
        int b = A[i];
 
        // Find the number of operations
        // required to reduce A[i] to
        // max_number
        while (b != max_number) {
 
            // Increment the number of
            // operations by 1
            ans++;
            b /= 2;
        }
    }
 
    // Print the answer
    cout << ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 1, 1, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    makeArrayEqual(arr, N);
 
    return 0;
}


Java
/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.Map;
import java.util.HashMap;
 
class GFG
{
   
  // Function to count minimum number of
  // division by 2 operations required to
  // make all array elements equal
  public static void makeArrayEqual(int A[], int n)
  {
     
    // Stores the frequencies of elements
    HashMap map = new HashMap<>();
 
    // Stores the maximum number to
    // which every array element
    // can be reduced to
    int max_number = 0;
 
    // Stores the minimum number
    // of operations required
    int ans = 0;
 
    // Traverse the array and store
    // the frequencies in the map
    for (int i = 0; i < n; i++) {
 
      int b = A[i];
 
      // Iterate while b > 0
      while (b>0) {
        Integer k = map.get(b);
        map.put(b, (k == null) ? 1 : k + 1);
 
        // Keep dividing b by 2
        b /= 2;
      }
    }
 
    // Iterate over the map to find
    // the required maximum number
    for (Map.Entry e :
         map.entrySet()) {
 
      // Check if the frequency
      // is equal to n
      if (e.getValue() == n) {
 
        // If true, store it in
        // max_number
        max_number = e.getKey();
      }
    }
 
    // Iterate over the array, A[]
    for (int i = 0; i < n; i++) {
      int b = A[i];
 
      // Find the number of operations
      // required to reduce A[i] to
      // max_number
      while (b != max_number) {
 
        // Increment the number of
        // operations by 1
        ans++;
        b /= 2;
      }
    }
 
    // Print the answer
    System.out.println(ans + " ");
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 3, 1, 1, 3 };
    int N = arr.length;
    makeArrayEqual(arr, N);
  }
}
 
// This code is contributed by aditya7409.


Python3
# Python 3 program for the above approach
 
# Function to count minimum number of
# division by 2 operations required to
# make all array elements equal
def makeArrayEqual(A, n):
   
  # Stores the frequencies of elements
  mp = dict()
 
  # Stores the maximum number to
  # which every array element
  # can be reduced to
  max_number = 0
 
  # Stores the minimum number
  # of operations required
  ans = 0
 
  # Traverse the array and store
  # the frequencies in the map
  for i in range(n):
    b = A[i]
 
      # Iterate while b > 0
    while (b>0):
      if (b in mp):
        mp[b] += 1
      else:
        mp[b] = mp.get(b,0)+1
 
      # Keep dividing b by 2
      b //= 2
 
  # Iterate over the map to find
  # the required maximum number
  for key,value in mp.items():
     
    # Check if the frequency
    # is equal to n
    if (value == n):
       
      # If true, store it in
      # max_number
      max_number = key
 
  # Iterate over the array, A[]
  for i in range(n):
    b = A[i]
 
      # Find the number of operations
      # required to reduce A[i] to
      # max_number
    while (b != max_number):
       
      # Increment the number of
      # operations by 1
      ans += 1
      b //= 2
 
  # Print the answer
  print(ans)
 
# Driver Code
if __name__ == '__main__':
  arr = [3, 1, 1, 3]
  N = len(arr)
  makeArrayEqual(arr, N)
 
  # This code is contributed by bgangwar59.


C#
using System;
using System.Collections.Generic;
 
class GFG
{
   
  // Function to count minimum number of
  // division by 2 operations required to
  // make all array elements equal
  public static void makeArrayEqual(int[] A, int n)
  {
     
    // Stores the frequencies of elements
    Dictionary map = new Dictionary();
 
    // Stores the maximum number to
    // which every array element
    // can be reduced to
    int max_number = 0;
 
    // Stores the minimum number
    // of operations required
    int ans = 0;
 
    // Traverse the array and store
    // the frequencies in the map
    for (int i = 0; i < n; i++) {
 
      int b = A[i];
 
      // Iterate while b > 0
      while (b > 0)
      {
        if (map.ContainsKey(b))
            map[b] ++;
        else
            map[b]=  1;
 
        // Keep dividing b by 2
        b /= 2;
      }
    }
 
    // Iterate over the map to find
    // the required maximum number
    foreach(KeyValuePair e in map)
    {
 
      // Check if the frequency
      // is equal to n
      if (e.Value == n) {
 
        // If true, store it in
        // max_number
        max_number = e.Key;
      }
    }
 
    // Iterate over the array, A[]
    for (int i = 0; i < n; i++) {
      int b = A[i];
 
      // Find the number of operations
      // required to reduce A[i] to
      // max_number
      while (b != max_number) {
 
        // Increment the number of
        // operations by 1
        ans++;
        b /= 2;
      }
    }
 
    // Print the answer
    Console.Write(ans + " ");
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int[] arr = { 3, 1, 1, 3 };
    int N = arr.Length;
    makeArrayEqual(arr, N);
  }
}
 
// This code is contributed by shubhamsingh10.


Javascript


输出:
2

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

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