📌  相关文章
📜  使除以2的除数最小以使所有数组元素相等

📅  最后修改于: 2021-05-14 00:22:23             🧑  作者: Mango

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

例子:

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

  • 初始化一个变量,例如ans ,以存储所需的最小除法运算次数。
  • 初始化一个HashMap,例如M ,以存储数组元素的频率。
  • 遍历数组arr [],直到发现任何数组元素arr [i]都大于0为止。继续将arr [i]除以2,并同时更新在Map M中获得的元素的频率。
  • 遍历HashMap并找到频率为N的最大元素。将其存储在maxNumber中
  • 再次,遍历数组ARR []和通过将ARR [I]2找到减少ARR所需的操作[I]MAXNUMBER的数量和添加操作的计数到可变ANS。
  • 完成上述步骤后,输出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.


输出:
2

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