📌  相关文章
📜  最大限度地减少替换数组中较大元素的元素数量所需的交换

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

给定一个由N 个元素组成的数组A[] ,任务是找到所需的最小交换次数,以使交换以替换原始数组中更高元素的数组元素最大化。

例子:

朴素的方法:解决问题的最简单的方法可以实现如下:

  • 按升序对数组进行排序。
  • 初始化两个变量, result index ,分别存储原始数组中已考虑到的计数和索引。
  • 迭代数组元素。对于任何元素A[i] ,转到数组中大于 a i 的值并相应地增加索引变量。
  • 找到大于A[i]的元素后,增加resultindex
  • 如果索引已到达数组的末尾,则不会留下任何元素与先前检查过的元素进行交换。
  • 因此,打印count

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Sort the array in ascending order
    sort(A, A + n);
 
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Iterate until a greater element
        // is found
        while (ind < n and A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n and A[ind] > A[i]) {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
int main()
{
 
    int A[] = { 4, 3, 3, 2, 5 };
    cout << countSwaps(A, 5);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int A[], int n)
{
    // Sort the array in ascending order
    Arrays.sort(A);
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++)
    {
 
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 4, 3, 3, 2, 5 };
    System.out.print(countSwaps(A, 5));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
 
    # Sort the array in ascending order
    A.sort()
 
    ind, res = 1, 0
 
    for i in range(n):
 
        # Iterate until a greater element
        # is found
        while (ind < n and A[ind] == A[i]):
 
            # Keep incrementing ind
            ind += 1
 
        # If a greater element is found
        if (ind < n and A[ind] > A[i]):
 
            # Increase count of swap
            res += 1
 
            # Increment ind
            ind += 1
 
        # If end of array is reached
        if (ind >= n):
            break
 
    # Return the answer
    return res
 
# Driver Code
A = [ 4, 3, 3, 2, 5 ]
 
print (countSwaps(A, 5))
 
# This code is contributed by chitranayal


C#
// C# Program to implement
// the above approach
using System;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []A, int n)
{
    // Sort the array in ascending order
    Array.Sort(A);
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++)
    {
 
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 4, 3, 3, 2, 5 };
    Console.Write(countSwaps(A, 5));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Stores the frequency of the
    // array elements
    map mp;
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++) {
 
        // Update frequency
        mp[A[i]]++;
 
        // Update maximum frequency
        max_frequency
            = max(max_frequency, mp[A[i]]);
    }
 
    return n - max_frequency;
}
 
// Driver Code
int main()
{
 
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    cout << countSwaps(A, 6);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int arr[], int n)
{
    // Stores the frequency of the
    // array elements
    HashMap mp = new HashMap();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++)
    {
 
        // Update frequency
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.max(max_frequency,
                                 mp.get(arr[i]));
    }
    return n - max_frequency;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    System.out.print(countSwaps(A, 6));
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 Program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
     
    # Stores the frequency of the
    # array elements
    mp = {}
 
    # Stores maximum frequency
    max_frequency = 0
 
    # Find the max frequency
    for i in range(n):
 
        # Update frequency
        if A[i] in mp:
            mp[A[i]] += 1
        else:
            mp[A[i]] = 1
 
        # Update maximum frequency
        max_frequency = max(max_frequency,
                            mp[A[i]])
 
    return n - max_frequency
   
# Driver code
if __name__ == "__main__":   
 
      A = [6, 5, 4, 3, 2, 1]
     
    # function call
    print(countSwaps(A, 6))
 
# This code is contributed by divyeshrabadiya07


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []arr, int n)
{
     
    // Stores the frequency of the
    // array elements
    Dictionary mp = new Dictionary();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for(int i = 0; i < n; i++)
    {
         
        // Update frequency
        if(mp.ContainsKey(arr[i]))
        {
            mp[arr[i]] = mp[arr[i]] + 1;
        }
        else
        {
            mp.Add(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.Max(max_frequency,
                                 mp[arr[i]]);
    }
    return n - max_frequency;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 6, 5, 4, 3, 2, 1 };
 
    // Function call
    Console.Write(countSwaps(A, 6));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
3

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

有效的方法:
由于两个不相等元素之间的任何交换都会导致一个元素替换更高的元素,因此可以观察到所需的最小交换次数是N –(数组元素的最大频率) 。因此,使用HashMap查找数组中出现频率最高的元素,并打印结果。

下面是上述方法的实现:

C++

// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Stores the frequency of the
    // array elements
    map mp;
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++) {
 
        // Update frequency
        mp[A[i]]++;
 
        // Update maximum frequency
        max_frequency
            = max(max_frequency, mp[A[i]]);
    }
 
    return n - max_frequency;
}
 
// Driver Code
int main()
{
 
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    cout << countSwaps(A, 6);
 
    return 0;
}

Java

// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int arr[], int n)
{
    // Stores the frequency of the
    // array elements
    HashMap mp = new HashMap();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++)
    {
 
        // Update frequency
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.max(max_frequency,
                                 mp.get(arr[i]));
    }
    return n - max_frequency;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    System.out.print(countSwaps(A, 6));
}
}
 
// This code is contributed by Rohit_ranjan

蟒蛇3

# Python3 Program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
     
    # Stores the frequency of the
    # array elements
    mp = {}
 
    # Stores maximum frequency
    max_frequency = 0
 
    # Find the max frequency
    for i in range(n):
 
        # Update frequency
        if A[i] in mp:
            mp[A[i]] += 1
        else:
            mp[A[i]] = 1
 
        # Update maximum frequency
        max_frequency = max(max_frequency,
                            mp[A[i]])
 
    return n - max_frequency
   
# Driver code
if __name__ == "__main__":   
 
      A = [6, 5, 4, 3, 2, 1]
     
    # function call
    print(countSwaps(A, 6))
 
# This code is contributed by divyeshrabadiya07

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []arr, int n)
{
     
    // Stores the frequency of the
    // array elements
    Dictionary mp = new Dictionary();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for(int i = 0; i < n; i++)
    {
         
        // Update frequency
        if(mp.ContainsKey(arr[i]))
        {
            mp[arr[i]] = mp[arr[i]] + 1;
        }
        else
        {
            mp.Add(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.Max(max_frequency,
                                 mp[arr[i]]);
    }
    return n - max_frequency;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 6, 5, 4, 3, 2, 1 };
 
    // Function call
    Console.Write(countSwaps(A, 6));
}
}
 
// This code is contributed by 29AjayKumar

Javascript

   
输出:
5

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

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