📌  相关文章
📜  计算递减到使所有数组元素相等所需的最接近的较小元素

📅  最后修改于: 2021-05-17 03:42:45             🧑  作者: Mango

给定一个由N个非负整数组成的数组arr [] ,任务是找到使所有数组元素相等所需的操作数。在每个操作中,任何数组元素都可以更改为最接近的较小数组元素。

例子:

方法:想法是使用排序算法和Map数据结构。请按照以下步骤解决问题:

  1. 初始化一个Map,以存储每个数组元素的频率,最小元素除外,其中最小键(K)是一组唯一元素,而值(V)是它们的频率。
  2. 根据键,以降序对地图进行排序。
  3. 0初始化两个变量ansprev_val分别存储当前答案和前缀和。
  4. 现在迭代Map并将每个元素的对应频率与prev_val一起添加ans中,ans = ans +(freq)+ prev_val
  5. 在迭代Map时,每次将prev_val增加当前元素的频率。
  6. 完全遍历地图后,请打印ans作为最小操作数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print the minimum number of
// decrements to make all elements equals
int MinimumNoOfOperations(int arr[], int n)
{
 
    // Find minimum element
    int min_ele = INT_MAX;
    for (int i = 0; i < n; ++i) {
        min_ele = min(min_ele, arr[i]);
    }
 
    // Stores frequencies of array elements
    map > mp;
 
    // Update frequencies in the Map
    for (int i = 0; i < n; ++i) {
 
        if (arr[i] == min_ele)
            continue;
        else
            mp[arr[i]]++;
    }
 
    // Iterate the map
    map::iterator it;
 
    // Stores the count of
    // decrements at each iteration
    int prev_val = 0;
 
    // Stores the total
    // count of derements
    int ans = 0;
 
    // Calculate the number of decrements
    for (it = mp.begin(); it != mp.end();
         ++it) {
 
        ans += (it->second + prev_val);
        prev_val += it->second;
    }
 
    // Return minimum operations
    return ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 5, 4, 3, 5, 4 };
 
    // Given size
    int size = sizeof(arr)
               / sizeof(arr[0]);
 
    // Function call
    cout << MinimumNoOfOperations(
        arr, size);
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
 
class solution{
    
// Function to print the minimum
// number of decrements to make
// all elements equals
static int MinimumNoOfOperations(int arr[],
                                 int n)
{
  // Find minimum element
  int min_ele = Integer.MAX_VALUE;
   
  for (int i = 0; i < n; ++i)
  {
    min_ele = Math.min(min_ele,
                       arr[i]);
  }
 
  // Stores frequencies of array
  // elements
  TreeMap mp =
          new TreeMap(
          Collections.reverseOrder());
 
  // Update frequencies in
  // the Map
  for (int i = 0; i < n; ++i)
  {
    if (arr[i] == min_ele)
      continue;
    else
      mp.put(arr[i],
      mp.getOrDefault(arr[i], 0) + 1);
  }
 
  // Stores the count of
  // decrements at each
  // iteration
  int prev_val = 0;
 
  // Stores the total
  // count of derements
  int ans = 0;
 
  // Calculate the number of
  // decrements
  for (Map.Entry it : mp.entrySet())
  {
    ans += (it.getValue() + prev_val);
    prev_val += it.getValue();
  }
 
  // Return minimum operations
  return ans;
}
 
// Driver Code
public static void main(String args[])
{
  // Given array
  int arr[] = {2, 5, 4, 3, 5, 4};
   
  // Given size
  int size = arr.length;
   
  // Function call
  System.out.println(
  MinimumNoOfOperations(arr, size));
}
}
 
// This code is contributed by bgangwar59


Python3
# Python3 program for the above approach
import sys
 
# Function to print the minimum number of
# decrements to make all elements equals
def MinimumNoOfOperations(arr, n):
     
    # Find minimum element
    min_ele = sys.maxsize
     
    for i in range(n):
        min_ele = min(min_ele, arr[i])
 
    # Stores frequencies of array elements
    mp = {}
 
    # Update frequencies in the Map
    for i in range(n):
        if (arr[i] == min_ele):
            continue
        else:
            mp[arr[i]] = mp.get(arr[i], 0) + 1
             
    # Stores the count of
    # decrements at each iteration
    prev_val = 0
 
    # Stores the total
    # count of derements
    ans = 0
 
    # Calculate the number of decrements
    for it in mp:
        ans += (mp[it] + prev_val)
        prev_val += mp[it]
 
    # Return minimum operations
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [ 2, 5, 4, 3, 5, 4 ]
 
    # Given size
    size = len(arr)
 
    # Function call
    print(MinimumNoOfOperations(arr, size))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System.Collections.Generic;
using System;
using System.Linq;
 
class GFG{
    
// Function to print the minimum
// number of decrements to make
// all elements equals
static int MinimumNoOfOperations(int []arr,
                                 int n)
{
   
  // Find minimum element
  int min_ele = 1000000000;
   
  for(int i = 0; i < n; ++i)
  {
      min_ele = Math.Min(min_ele, arr[i]);
  }
 
  // Stores frequencies of array
  // elements
  Dictionary mp = new Dictionary();
 
  // Update frequencies in
  // the Map
  for(int i = 0; i < n; ++i)
  {
    if (arr[i] == min_ele)
      continue;
    else
    {
      if (mp.ContainsKey(arr[i]) == true)
        mp[arr[i]] += 1;
      else
        mp[arr[i]] = 1;   
    }
  }
 
  // Stores the count of
  // decrements at each
  // iteration
  int prev_val = 0;
 
  // Stores the total
  // count of derements
  int ans = 0;
 
  // Calculate the number of
  // decrements
  var val = mp.Keys.ToList();
  foreach(var key in val)
  {
    ans += (mp[key] + prev_val);
    prev_val += mp[key];
  }
   
  // Return minimum operations
  return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
   
  // Given array
  int []arr = { 2, 5, 4, 3, 5, 4 };
   
  // Given size
  int size = arr.Length;
   
  // Function call
  Console.WriteLine(MinimumNoOfOperations(
    arr, size));
}
}
 
// This code is contributed by Stream_Cipher


输出:
11

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