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

📅  最后修改于: 2021-10-27 08:00:50             🧑  作者: Mango

给定一个包含 n 个正整数的数组。我们需要找到使所有元素相等的最小操作次数。我们可以对数组元素上的任何元素执行加法、乘法、减法或除法。
例子:

Input : arr[] = {1, 2, 3, 4}
Output : 3
Since all elements are different, 
we need to perform at least three
operations to make them same. For
example, we can make them all 1
by doing three subtractions. Or make
them all 3 by doing three additions.

Input : arr[] = {1, 1, 1, 1}
Output : 0

为了使所有元素相等,您可以选择一个目标值,然后您可以使所有元素都相等。现在,要将单个元素转换为目标值,您只需执行一次操作。通过这种方式,您最多可以完成 n 次操作,但您必须尽量减少此操作次数,为此您选择的目标非常重要,因为如果您选择数组中频率为 x 的目标,那么您只需执行nx 更多操作,因为您已经有 x 个元素等于您的目标值。所以最后,我们的任务被简化为找到频率最大的元素。这可以通过不同的方法来实现,例如 O(n^2) 中的迭代方法、O(nlogn) 中的排序和 O(n) 时间复杂度中的散列。

C++
// CPP program to find the minimum number of
// operations required to make all elements
// of array equal
#include 
using namespace std;
 
// function for min operation
int minOperation (int arr[], int n)
{
    // Insert all elements in hash.
    unordered_map hash;
    for (int i=0; i


Java
// JAVA Code For Minimum operation to make
// all elements equal in array
import java.util.*;
 
class GFG {
     
    // function for min operation
    public static int minOperation (int arr[], int n)
    {
        // Insert all elements in hash.
       HashMap hash = new HashMap();
         
        for (int i=0; i s = hash.keySet();
         
        for (int i : s)
            if (max_count < hash.get(i))
                max_count = hash.get(i);
      
        // return result
        return (n - max_count);
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = {1, 5, 2, 1, 3, 2, 1};
        int n = arr.length;
        System.out.print(minOperation(arr, n));
             
    }
}
   
// This code is contributed by Arnav Kr. Mandal.


Python3
# Python3 program to find the minimum
# number of operations required to
# make all elements of array equal
from collections import defaultdict
 
# Function for min operation
def minOperation(arr, n):
 
    # Insert all elements in hash.
    Hash = defaultdict(lambda:0)
    for i in range(0, n):
        Hash[arr[i]] += 1
 
    # find the max frequency
    max_count = 0
    for i in Hash:
        if max_count < Hash[i]:
            max_count = Hash[i]
 
    # return result
    return n - max_count
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 5, 2, 1, 3, 2, 1]
    n = len(arr)
    print(minOperation(arr, n))
     
# This code is contributed
# by Rituraj Jain


C#
// C# Code For Minimum operation to make
// all elements equal in array
using System;
using System.Collections.Generic;
     
class GFG
{
     
    // function for min operation
    public static int minOperation (int []arr, int n)
    {
        // Insert all elements in hash.
        Dictionary m = new Dictionary();
        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);
            }
        }
         
        // find the max frequency
        int max_count = 0;
        HashSet s = new HashSet(m.Keys);
         
        foreach (int i in s)
            if (max_count < m[i])
                max_count = m[i];
     
        // return result
        return (n - max_count);
    }
     
    /* Driver code */
    public static void Main(String[] args)
    {
        int []arr = {1, 5, 2, 1, 3, 2, 1};
        int n = arr.Length;
        Console.Write(minOperation(arr, n));
             
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

4

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