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

📅  最后修改于: 2021-05-17 18:18:35             🧑  作者: Mango

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

例子:

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

  • 初始化一个变量,例如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)