📌  相关文章
📜  当元素及其索引除以 K 时,最小化交换以使余数相等

📅  最后修改于: 2022-05-13 01:56:09.511000             🧑  作者: Mango

当元素及其索引除以 K 时,最小化交换以使余数相等

给定一个正整数数组arr[]和一个正数K,任务是找到所需的最小元素交换,使得对于索引i 处的每个元素,以下条件成立:

例子:

方法:给定的问题可以使用贪心方法来解决。这个想法是遍历数组并进行交换,以便尽可能将两个元素带到它们的准确位置,否则将正确的元素带到当前位置。可以按照以下步骤解决问题:

  • 通过比较index % kelement % k的频率来检查是否可以完成任务
    • 如果频率不匹配,则返回 -1
  • 迭代数组并在每个索引处i
    • 如果arr[i] % 3 == i % 3则继续下一个索引
    • 否则,如果arr[i] % 3 != i % 3然后找到从i+1N-1的索引j ,其中i % 3 = arr[j] % 3j % 3 = arr[i] % 3将两个元素带到他们的准确位置
    • 否则,通过从i+1迭代到N-1来找到索引k,其中i % 3 = arr[k] % 3,并交换元素

下面是上述方法的实现:

C++
// C++ implementation for the above approach
 
#include 
using namespace std;
 
// Function to swap the values
void swapping(int arr[], int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
 
// Function to find the minimum swaps
// required such that arr[i] % k = i % k
int CountMinSwaps(int arr[], int N, int K)
{
 
    // initialize matrix with 0 values
    int mat[K][2] = { 0 };
 
    int i, j, count = 0;
 
    for (i = 0; i < N; i++) {
 
        // Count the frequency of
        // index % k
        mat[i % K][0] += 1;
 
        // Count the frequency of
        // index % k
        mat[arr[i] % K][1] += 1;
    }
 
    // If the count of indexes % k and
    // array elements % K are not same
    // then the task is not possible
    // therefore return -1
    for (i = 0; i < K; i++) {
 
        if (mat[i][0] != mat[i][1])
            return -1;
    }
 
    // Count the swaps
    for (i = 0; i < N; i++) {
 
        // If condition is already true
        // move to the next index
        if (i % K == arr[i] % K)
            continue;
 
        // Current index remainder
        int ind = i % K;
 
        // Current element remainder
        int ele = arr[i] % K;
 
        // Boolean variable to indicate
        // if the swap was made with the
        // element such that both the swapped
        // elements would be at correct place
        bool swapped = false;
 
        // Search for the element from
        // i + 1 till end of the array
        for (j = i + 1; j < N; j++) {
 
            // Expected index remainder
            int ind_exp = j % K;
 
            // Expected element remainder
            int ele_exp = arr[j] % K;
 
            if (ind == ele_exp
                && ele == ind_exp) {
 
                // Swap the element if found
                swapping(arr, i, j);
 
                // Update the boolean
                // variable swap to true
                swapped = true;
 
                // Increment count of swaps
                count++;
 
                break;
            }
        }
 
        // If the swap didnt take place
        if (swapped == false) {
 
            // Iterate from i+1 till end and
            // find the accurate element for
            // the current index
            for (j = i + 1; j < N; j++) {
 
                // Expected element remainder
                int ele_exp = arr[j] % K;
 
                if (ind == ele_exp) {
 
                    // Swap after finding
                    // the element
                    swapping(arr, i, j);
 
                    // Increment the count
                    count++;
 
                    break;
                }
            }
        }
    }
 
    // Return the result
    return count;
}
 
// Driver code
int main()
{
 
    int arr[6] = { 0, 1, 2, 3, 4, 5 };
    int K = 1;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Call the function
    int swaps = CountMinSwaps(arr, N, K);
 
    // Print the answer
    cout << swaps << endl;
}


Java
// Java implementation for the above approach
public class GFG {
     
    // Function to swap the values
    static void swapping(int arr[], int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
     
    // Function to find the minimum swaps
    // required such that arr[i] % k = i % k
    static int CountMinSwaps(int arr[], int N, int K)
    {
     
        // initialize matrix with 0 values
        int mat[][] = new int[K][2] ;
        int i, j, count = 0;
     
        for (i = 0; i < N; i++) {
     
            // Count the frequency of
            // index % k
            mat[i % K][0] += 1;
     
            // Count the frequency of
            // index % k
            mat[arr[i] % K][1] += 1;
        }
     
        // If the count of indexes % k and
        // array elements % K are not same
        // then the task is not possible
        // therefore return -1
        for (i = 0; i < K; i++) {
     
            if (mat[i][0] != mat[i][1])
                return -1;
        }
     
        // Count the swaps
        for (i = 0; i < N; i++) {
     
            // If condition is already true
            // move to the next index
            if (i % K == arr[i] % K)
                continue;
     
            // Current index remainder
            int ind = i % K;
     
            // Current element remainder
            int ele = arr[i] % K;
     
            // Boolean variable to indicate
            // if the swap was made with the
            // element such that both the swapped
            // elements would be at correct place
            boolean swapped = false;
     
            // Search for the element from
            // i + 1 till end of the array
            for (j = i + 1; j < N; j++) {
     
                // Expected index remainder
                int ind_exp = j % K;
     
                // Expected element remainder
                int ele_exp = arr[j] % K;
     
                if (ind == ele_exp
                    && ele == ind_exp) {
     
                    // Swap the element if found
                    swapping(arr, i, j);
     
                    // Update the boolean
                    // variable swap to true
                    swapped = true;
     
                    // Increment count of swaps
                    count++;
     
                    break;
                }
            }
     
            // If the swap didnt take place
            if (swapped == false) {
     
                // Iterate from i+1 till end and
                // find the accurate element for
                // the current index
                for (j = i + 1; j < N; j++) {
     
                    // Expected element remainder
                    int ele_exp = arr[j] % K;
     
                    if (ind == ele_exp) {
     
                        // Swap after finding
                        // the element
                        swapping(arr, i, j);
     
                        // Increment the count
                        count++;
     
                        break;
                    }
                }
            }
        }
     
        // Return the result
        return count;
    }
     
    // Driver code
    public static void main (String[] args)
    {
     
        int arr[] = { 0, 1, 2, 3, 4, 5 };
        int K = 1;
        int N = arr.length;
     
        // Call the function
        int swaps = CountMinSwaps(arr, N, K);
     
        // Print the answer
        System.out.println(swaps);
    }
}
 
// This code is contributed by AnkThon


Python3
# python implementation for the above approach
 
# Function to swap the values
def swapping(arr, i, j):
 
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
 
# Function to find the minimum swaps
# required such that arr[i] % k = i % k
def CountMinSwaps(arr, N, K):
 
    # initialize matrix with 0 values
    mat = [[0 for _ in range(2)] for _ in range(K)]
 
    count = 0
 
    for i in range(0, N):
 
        # Count the frequency of
        # index % k
        mat[i % K][0] += 1
 
        # Count the frequency of
        # index % k
        mat[arr[i] % K][1] += 1
 
    # If the count of indexes % k and
    # array elements % K are not same
    # then the task is not possible
    # therefore return -1
    for i in range(0, K):
 
        if (mat[i][0] != mat[i][1]):
            return -1
 
    # Count the swaps
    for i in range(0, N):
 
        # If condition is already true
        # move to the next index
        if (i % K == arr[i] % K):
            continue
 
        # Current index remainder
        ind = i % K
 
        # Current element remainder
        ele = arr[i] % K
 
        # Boolean variable to indicate
        # if the swap was made with the
        # element such that both the swapped
        # elements would be at correct place
        swapped = False
 
        # Search for the element from
        # i + 1 till end of the array
        for j in range(i+1, N):
 
            # Expected index remainder
            ind_exp = j % K
 
            # Expected element remainder
            ele_exp = arr[j] % K
 
            if (ind == ele_exp and ele == ind_exp):
 
                # Swap the element if found
                swapping(arr, i, j)
 
                # Update the boolean
                # variable swap to true
                swapped = True
 
                # Increment count of swaps
                count += 1
 
                break
 
        # If the swap didnt take place
        if (swapped == False):
 
            # Iterate from i+1 till end and
            # find the accurate element for
            # the current index
            for j in range(i+1, N):
 
                # Expected element remainder
                ele_exp = arr[j] % K
 
                if (ind == ele_exp):
 
                    # Swap after finding
                    # the element
                    swapping(arr, i, j)
 
                    # Increment the count
                    count += 1
 
                    break
 
    # Return the result
    return count
 
# Driver code
if __name__ == "__main__":
 
    arr = [0, 1, 2, 3, 4, 5]
    K = 1
    N = len(arr)
 
    # Call the function
    swaps = CountMinSwaps(arr, N, K)
 
    # Print the answer
    print(swaps)
 
# This code is contributed by rakeshsahni


C#
// C# implementation for the above approach
 
using System;
 
public class GFG
{
 
    // Function to swap the values
    static void swapping(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    // Function to find the minimum swaps
    // required such that arr[i] % k = i % k
    static int CountMinSwaps(int[] arr, int N, int K)
    {
 
        // initialize matrix with 0 values
        int[,] mat = new int[K, 2];
        int i, j, count = 0;
 
        for (i = 0; i < N; i++)
        {
 
            // Count the frequency of
            // index % k
            mat[i % K, 0] += 1;
 
            // Count the frequency of
            // index % k
            mat[arr[i] % K, 1] += 1;
        }
 
        // If the count of indexes % k and
        // array elements % K are not same
        // then the task is not possible
        // therefore return -1
        for (i = 0; i < K; i++)
        {
 
            if (mat[i, 0] != mat[i, 1])
                return -1;
        }
 
        // Count the swaps
        for (i = 0; i < N; i++)
        {
 
            // If condition is already true
            // move to the next index
            if (i % K == arr[i] % K)
                continue;
 
            // Current index remainder
            int ind = i % K;
 
            // Current element remainder
            int ele = arr[i] % K;
 
            // Boolean variable to indicate
            // if the swap was made with the
            // element such that both the swapped
            // elements would be at correct place
            bool swapped = false;
 
            // Search for the element from
            // i + 1 till end of the array
            for (j = i + 1; j < N; j++)
            {
 
                // Expected index remainder
                int ind_exp = j % K;
 
                // Expected element remainder
                int ele_exp = arr[j] % K;
 
                if (ind == ele_exp
                    && ele == ind_exp)
                {
 
                    // Swap the element if found
                    swapping(arr, i, j);
 
                    // Update the boolean
                    // variable swap to true
                    swapped = true;
 
                    // Increment count of swaps
                    count++;
 
                    break;
                }
            }
 
            // If the swap didnt take place
            if (swapped == false)
            {
 
                // Iterate from i+1 till end and
                // find the accurate element for
                // the current index
                for (j = i + 1; j < N; j++)
                {
 
                    // Expected element remainder
                    int ele_exp = arr[j] % K;
 
                    if (ind == ele_exp)
                    {
 
                        // Swap after finding
                        // the element
                        swapping(arr, i, j);
 
                        // Increment the count
                        count++;
 
                        break;
                    }
                }
            }
        }
 
        // Return the result
        return count;
    }
 
    // Driver code
    public static void Main()
    {
 
        int[] arr = { 0, 1, 2, 3, 4, 5 };
        int K = 1;
        int N = arr.Length;
 
        // Call the function
        int swaps = CountMinSwaps(arr, N, K);
 
        // Print the answer
        Console.Write(swaps);
    }
}
 
// This code is contributed by Saurabh Jaiswal


Javascript


输出
0

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