📌  相关文章
📜  找到使所有数组元素相等所需的最小操作数

📅  最后修改于: 2021-04-22 02:44:54             🧑  作者: Mango

给定大小为N的数组arr [] 。任务是通过应用以下操作最少次数来使所有数组元素相等:

  1. 选择一对索引(i,j) ,使得| i – j | = 1 (索引i和j相邻)并设置arr [i] = arr [i] + | arr [i] – arr [j] |
  2. 选择一对索引(i,j) ,使得| i – j | = 1 (索引i和j相邻)并设置arr [i] = arr [i] – | arr [i] – arr [j] |

例子:

方法:让我们找到数组中最频繁的元素(使用映射存储所有元素的频率)。令此元素为x 。如果我们更仔细地观察操作,我们可以看到这些操作的一部分意味着将元素p设置为元素q 。如果p 则需要执行第一个操作,否则执行第二个操作。

现在,考虑最佳答案中的运算次数。显然,我们至少需要n – freq(x)个运算来均衡所有元素。同样很明显,我们总是可以使用n – freq(x)这样的操作来完成操作,这是所需的最少操作数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the minimum operations
// required to make all array elements equal
int minOperations(int arr[], int n)
{
  
    // To store the frequency
    // of all the array elements
    unordered_map mp;
  
    // Traverse through array elements and
    // update frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
  
    // To store the maximum frequency
    // of an element from the array
    int maxFreq = INT_MIN;
  
    // Traverse through the map and find
    // the maximum frequency for any element
    for (auto x : mp)
        maxFreq = max(maxFreq, x.second);
  
    // Return the minimum operations required
    return (n - maxFreq);
}
  
// Driver code
int main()
{
    int arr[] = { 2, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << minOperations(arr, n);
  
    return 0;
}


Java
// Java implementation of the above approach 
import java.util.*;
  
class GFG
{
  
    // Function to return the minimum operations 
    // required to make all array elements equal 
    static int minOperations(int arr[], int n) 
    {
  
        // To store the frequency 
        // of all the array elements 
        HashMap mp = new HashMap();
  
        // Traverse through array elements and 
        // update frequencies 
        for (int i = 0; i < n; i++) 
        {
            if (mp.containsKey(arr[i])) 
            {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            } 
            else
            {
                mp.put(arr[i], 1);
            }
        }
  
        // To store the maximum frequency 
        // of an element from the array 
        int maxFreq = Integer.MIN_VALUE;
  
        // Traverse through the map and find 
        // the maximum frequency for any element 
        maxFreq = Collections.max(mp.entrySet(), 
                Comparator.comparingInt(Map.Entry::getKey)).getValue();
                  
        // Return the minimum operations required 
        return (n - maxFreq);
    }
  
    // Driver code 
    public static void main(String[] args)
    {
        int arr[] = {2, 4, 6};
        int n = arr.length;
        System.out.println(minOperations(arr, n));
    }
}
  
/* This code contributed by PrinciRaj1992 */


Python3
# Python3 implementation of the approach
import sys
  
# Function to return the minimum operations
# required to make all array elements equal
def minOperations(arr, n) :
  
    # To store the frequency
    # of all the array elements
    mp = dict.fromkeys(arr, 0);
  
    # Traverse through array elements and
    # update frequencies
    for i in range(n) :
        mp[arr[i]] += 1;
  
    # To store the maximum frequency
    # of an element from the array
    maxFreq = -(sys.maxsize - 1);
  
    # Traverse through the map and find
    # the maximum frequency for any element
    for key in mp :
        maxFreq = max(maxFreq, mp[key]);
  
    # Return the minimum operations required
    return (n - maxFreq);
  
# Driver code
if __name__ == "__main__" :
  
    arr = [ 2, 4, 6 ];
    n = len(arr) ;
  
    print(minOperations(arr, n));
  
# This code is contributed by Ryuga


C#
// C# implementation of the above approach 
using System;
using System.Linq;
using System.Collections.Generic; 
  
class GFG
{
  
    // Function to return the minimum operations 
    // required to make all array elements equal 
    static int minOperations(int []arr, int n) 
    {
  
        // To store the frequency 
        // of all the array elements 
        Dictionary m = new Dictionary();
  
        // Traverse through array elements and 
        // update frequencies 
        for (int i = 0; i < n; i++) 
        {
            if(m.ContainsKey(arr[i]))
            {
                var val = m[arr[i]];
                m.Remove(arr[i]);
                m.Add(arr[i], val + 1); 
            }
            else
            {
                m.Add(arr[i], 1);
            }     
        }
  
        // To store the maximum frequency 
        // of an element from the array 
        int maxFreq = int.MinValue;
  
        // Traverse through the map and find 
        // the maximum frequency for any element 
        maxFreq = m.Values.Max();
                  
        // Return the minimum operations required 
        return (n - maxFreq);
    }
  
    // Driver code 
    public static void Main(String[] args)
    {
        int []arr = {2, 4, 6};
        int n = arr.Length;
        Console.WriteLine(minOperations(arr, n));
    }
}
  
// This code contributed by Rajput-Ji


输出:
2