📌  相关文章
📜  使两个给定数组之一的所有元素相等所需的相似索引元素的最小交换

📅  最后修改于: 2021-09-04 07:52:17             🧑  作者: Mango

给定两个大小为N 的数组A[]B[] ,任务是计算使两个给定数组之一相等所需的相似索引元素的最小交换次数。如果不可能使数组的所有元素相等,则打印-1

例子:

方法:可以使用Hashing解决问题。请按照以下步骤解决问题:

  • 初始化一个变量,比如minSwaps ,以存储所需的最小交换次数,这样至少一个数组只包含一个不同的值。
  • 初始化另一个变量,比如swapsRequired ,以存储所需的交换次数,这样至少一个数组只包含一个不同的值。
  • 初始化一个数组,比如countA[] ,以存储数组A[]的每个不同元素的频率。
  • 初始化一个数组,比如countB[] ,以存储数组B[]的每个不同元素的频率。
  • 初始化一个数组,比如countAB[] ,以存储每个不同元素的频率,这些元素出现在A[]B[]的相同索引处。
  • 使用变量i遍历两个数组,并检查(countA[i] + countB[i] – countAB[i] == N) 的值是否为真。如果发现为真,则更新swapsRequired = min(countA[i], countB[i]) – countAB[i]并更新minSwaps = min(minSwaps, swapsRequired)
  • 最后,打印minSwaps的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to count minimum number of swap
// require such that either of the array
// contain a single distinct value
int minimumNumOfSwap(int A[], int B[], int N)
{
 
    // Stores largest element of
    // the array A[]
    int MaxA = *max_element(A, A + N);
 
    // Stores largest element of
    // the array B[]
    int MaxB = *max_element(B, B + N);
 
    // Stores maximum value
    // of (MaxA, MaxB)
    int M = max(MaxA, MaxB);
 
    // Store the frequency of
    // each distinct element of A[]
    int countA[M + 1] = { 0 };
 
    // Store the frequency of
    // each distinct element of B[]
    int countB[M + 1] = { 0 };
 
    // Store frequency of each distinct
    // element which is present at
    // same indices in A[] and B[]
    int equalAB[M + 1] = { 0 };
 
    // Stores count of swaps required such
    // that at least one of the arrays
    // contain a single distinct value
    int swapsRequired;
 
    // Stores minimum count of swaps required
    // such that at least one of the arrays
    // contain single distinct value
    int minSwaps = N;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Update frequency of A[i]
        countA[A[i]]++;
 
        // Update frequency of B[i]
        countB[B[i]]++;
 
        // If A[i] and B[i] are equal
        if (A[i] == B[i]) {
 
            // Update frequency
            // of A[i] and B[i]
            equalAB[A[i]]++;
        }
    }
 
    // Traverse each distinct
    // element of A[] and B[]
    for (int i = 1; i <= M; i++) {
 
        // If sum of frequency of i in A and B
        // present at different indices is N
        if ((countA[i] + countB[i]
             - equalAB[i])
            == N) {
 
            // Update swapsRequired
            swapsRequired
                = min(countA[i], countB[i])
                  - equalAB[i];
 
            // Update minSwaps
            minSwaps = min(minSwaps,
                           swapsRequired);
        }
    }
 
    // If minSwaps is equal to N
    if (minSwaps == N) {
        return -1;
    }
    else {
        return minSwaps;
    }
}
 
// Driver Code
int main()
{
    int A[] = { 3, 4, 1, 3, 1, 3, 4 };
    int B[] = { 1, 3, 3, 1, 3, 4, 3 };
 
    int N = sizeof(A) / sizeof(A[0]);
 
    cout << minimumNumOfSwap(A, B, N);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
public class Main
{
    // Function to count minimum number of swap
    // require such that either of the array
    // contain a single distinct value
    public static int minimumNumOfSwap(int A[], int B[], int N)
    {
       
        // Stores largest element of
        // the array A[]
        int MaxA = Arrays.stream(A).max().getAsInt();
       
        // Stores largest element of
        // the array B[]
        int MaxB = Arrays.stream(B).max().getAsInt();
       
        // Stores maximum value
        // of (MaxA, MaxB)
        int M = Math.max(MaxA, MaxB);
       
        // Store the frequency of
        // each distinct element of A[]
        int[] countA = new int[M + 1];
       
        // Store the frequency of
        // each distinct element of B[]
        int[] countB = new int[M + 1];
       
        // Store frequency of each distinct
        // element which is present at
        // same indices in A[] and B[]
        int[] equalAB = new int[M + 1];
       
        // Stores count of swaps required such
        // that at least one of the arrays
        // contain a single distinct value
        int swapsRequired;
       
        // Stores minimum count of swaps required
        // such that at least one of the arrays
        // contain single distinct value
        int minSwaps = N;
       
        // Traverse the array
        for (int i = 0; i < N; i++)
        {
       
            // Update frequency of A[i]
            countA[A[i]]++;
       
            // Update frequency of B[i]
            countB[B[i]]++;
       
            // If A[i] and B[i] are equal
            if (A[i] == B[i])
            {
       
                // Update frequency
                // of A[i] and B[i]
                equalAB[A[i]]++;
            }
        }
       
        // Traverse each distinct
        // element of A[] and B[]
        for (int i = 1; i <= M; i++)
        {
       
            // If sum of frequency of i in A and B
            // present at different indices is N
            if ((countA[i] + countB[i]
                 - equalAB[i])
                == N)
            {
       
                // Update swapsRequired
                swapsRequired
                    = Math.min(countA[i], countB[i])
                      - equalAB[i];
       
                // Update minSwaps
                minSwaps = Math.min(minSwaps,
                               swapsRequired);
            }
        }
       
        // If minSwaps is equal to N
        if (minSwaps == N)
        {
            return -1;
        }
        else
        {
            return minSwaps;
        }
    }
 
    public static void main(String[] args)
    {
        int A[] = { 3, 4, 1, 3, 1, 3, 4 };
        int B[] = { 1, 3, 3, 1, 3, 4, 3 };
       
        int N = A.length;
      
        System.out.println(minimumNumOfSwap(A, B, N));
    }
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program to implement
# the above approach
 
# Function to count minimum number of swap
# require such that either of the array
# contain a single distinct value
def minimumNumOfSwap(A, B, N) :
 
    # Stores largest element of
    # the array A[]
    MaxA = max(A)
 
    # Stores largest element of
    # the array B[]
    MaxB = max(B)
 
    # Stores maximum value
    # of (MaxA, MaxB)
    M = max(MaxA, MaxB)
 
    # Store the frequency of
    # each distinct element of A[]
    countA = [0] * (M + 1)
 
    # Store the frequency of
    # each distinct element of B[]
    countB = [0] * (M + 1)
 
    # Store frequency of each distinct
    # element which is present at
    # same indices in A[] and B[]
    equalAB = [0] * (M + 1)
 
    # Stores count of swaps required such
    # that at least one of the arrays
    # contain a single distinct value
    swapsRequired = 0
 
    # Stores minimum count of swaps required
    # such that at least one of the arrays
    # contain single distinct value
    minSwaps = N
 
    # Traverse the array
    for i in range(N) :
         
        # Update frequency of A[i]
        countA[A[i]] += 1
 
        # Update frequency of B[i]
        countB[B[i]] += 1
 
        # If A[i] and B[i] are equal
        if (A[i] == B[i]) :
 
            # Update frequency
            # of A[i] and B[i]
            equalAB[A[i]] += 1
 
    # Traverse each distinct
    # element of A[] and B[]
    for i in range(1, M + 1) :
 
        # If sum of frequency of i in A and B
        # present at different indices is N
        if ((countA[i] + countB[i] - equalAB[i]) == N) :
 
            # Update swapsRequired
            swapsRequired = min(countA[i], countB[i]) - equalAB[i]
 
            # Update minSwaps
            minSwaps = min(minSwaps, swapsRequired)
 
    # If minSwaps is equal to N
    if (minSwaps == N) :
        return -1
    else :
        return minSwaps
 
# Driver code
A = [ 3, 4, 1, 3, 1, 3, 4 ]
B = [ 1, 3, 3, 1, 3, 4, 3 ]
 
N = len(A)
 
print(minimumNumOfSwap(A, B, N))
 
# This code is contributed by divyesh072019


C#
// C# program to implement
// the above approach
using System;
using System.Linq;
 
class GFG{
     
// Function to count minimum number of swap
// require such that either of the array
// contain a single distinct value
public static int minimumNumOfSwap(int []A, int []B,
                                   int N)
{
     
    // Stores largest element of
    // the array A[]
    int MaxA = A.Max();
   
    // Stores largest element of
    // the array B[]
    int MaxB = B.Max();
   
    // Stores maximum value
    // of (MaxA, MaxB)
    int M = Math.Max(MaxA, MaxB);
   
    // Store the frequency of
    // each distinct element of A[]
    int[] countA = new int[M + 1];
   
    // Store the frequency of
    // each distinct element of B[]
    int[] countB = new int[M + 1];
   
    // Store frequency of each distinct
    // element which is present at
    // same indices in A[] and B[]
    int[] equalAB = new int[M + 1];
   
    // Stores count of swaps required such
    // that at least one of the arrays
    // contain a single distinct value
    int swapsRequired;
   
    // Stores minimum count of swaps required
    // such that at least one of the arrays
    // contain single distinct value
    int minSwaps = N;
   
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of A[i]
        countA[A[i]]++;
   
        // Update frequency of B[i]
        countB[B[i]]++;
   
        // If A[i] and B[i] are equal
        if (A[i] == B[i])
        {
             
            // Update frequency
            // of A[i] and B[i]
            equalAB[A[i]]++;
        }
    }
   
    // Traverse each distinct
    // element of A[] and B[]
    for(int i = 1; i <= M; i++)
    {
         
        // If sum of frequency of i in A and B
        // present at different indices is N
        if ((countA[i] + countB[i] - equalAB[i]) == N)
        {
             
            // Update swapsRequired
            swapsRequired = Math.Min(countA[i],
                                     countB[i]) -
                                     equalAB[i];
   
            // Update minSwaps
            minSwaps = Math.Min(minSwaps,
                                swapsRequired);
        }
    }
   
    // If minSwaps is equal to N
    if (minSwaps == N)
    {
        return -1;
    }
    else
    {
        return minSwaps;
    }
}
 
// Driver Code
public static void Main(string[] args)
{
    int []A = { 3, 4, 1, 3, 1, 3, 4 };
    int []B = { 1, 3, 3, 1, 3, 4, 3 };
   
    int N = A.Length;
  
    Console.WriteLine(minimumNumOfSwap(A, B, N));
}
}
 
// This code is contributed by AnkitRai01


Javascript


输出:
3

时间复杂度: O(M + N),其中 M 是 A[] 和 B[] 中最大的元素。
辅助空间: O(M)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live