📌  相关文章
📜  将相似元素布置在一起的最小相邻交换数

📅  最后修改于: 2021-04-29 06:06:44             🧑  作者: Mango

给定2 * N个正整数的数组,其中每个数组元素位于1到N之间,并且在数组中恰好出现两次。任务是找到将所有相似的数组元素布置在一起所需的最少数量的相邻交换。

注意:不必对最终数组(执行交换之后)进行排序。

例子:

方法:可以使用贪婪方法解决此问题。以下是步骤:

  1. 如果未对curr_ele执行交换操作,则保留一个数组Visited [] ,该数组指示visits [curr_ele]为false。
  2. 遍历原始数组,如果尚未访问当前数组元素(即, visited [arr [curr_ele]] = false) ,则将其设置为true并遍历从当前位置到数组末尾的另一个循环。
  3. 初始化变量计数,该变量计数将确定将当前元素的伙伴放置在其正确位置所需的交换次数。
  4. 在嵌套循环中,仅当Visited [curr_ele]为false时(因为为true,则意味着curr_ele已被放置在其正确的位置),增量计数。
  5. 如果在嵌套循环中找到了当前元素的伙伴,则将count的值加到总答案中。

下面是上述方法的实现:

C++
// C++ Program to find the minimum number of
// adjacent swaps to arrange similar items together
  
#include 
using namespace std;
  
// Function to find minimum swaps
int findMinimumAdjacentSwaps(int arr[], int N)
{
    // visited array to check if value is seen already
    bool visited[N + 1];
  
    int minimumSwaps = 0;
    memset(visited, false, sizeof(visited));
  
    for (int i = 0; i < 2 * N; i++) {
  
        // If the arr[i] is seen first time
        if (visited[arr[i]] == false) {
            visited[arr[i]] = true;
  
            // stores the number of swaps required to
            // find the correct position of current
            // element's partner
            int count = 0;
  
            for (int j = i + 1; j < 2 * N; j++) {
  
                // Increment count only if the current
                // element has not been visited yet (if is
                // visited, means it has already been placed
                // at its correct position)
                if (visited[arr[j]] == false)
                    count++;
  
                // If current element's partner is found
                else if (arr[i] == arr[j])
                    minimumSwaps += count;
            }
        }
    }
    return minimumSwaps;
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 3, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    N /= 2;
  
    cout << findMinimumAdjacentSwaps(arr, N) << endl;
    return 0;
}


Java
// Java Program to find the minimum number of
// adjacent swaps to arrange similar items together
import java.util.*;
  
class solution
{
  
// Function to find minimum swaps
static int findMinimumAdjacentSwaps(int arr[], int N)
{
    // visited array to check if value is seen already
    boolean[] visited = new boolean[N + 1];
  
    int minimumSwaps = 0;
    Arrays.fill(visited,false);
     
  
    for (int i = 0; i < 2 * N; i++) {
  
        // If the arr[i] is seen first time
        if (visited[arr[i]] == false) {
            visited[arr[i]] = true;
  
            // stores the number of swaps required to
            // find the correct position of current
            // element's partner
            int count = 0;
  
            for (int j = i + 1; j < 2 * N; j++) {
  
                // Increment count only if the current
                // element has not been visited yet (if is
                // visited, means it has already been placed
                // at its correct position)
                if (visited[arr[j]] == false)
                    count++;
  
                // If current element's partner is found
                else if (arr[i] == arr[j])
                    minimumSwaps += count;
            }
        }
    }
    return minimumSwaps;
}
  
// Driver Code
public static void main(String args[])
{
    int arr[] = { 1, 2, 3, 3, 1, 2 };
    int N = arr.length;
    N /= 2;
  
    System.out.println(findMinimumAdjacentSwaps(arr, N));
      
}
}
// This code is contributed by
// Sanjit_Prasad


Python3
# Python3 Program to find the minimum number of 
# adjacent swaps to arrange similar items together 
  
# Function to find minimum swaps 
def findMinimumAdjacentSwaps(arr, N) :
      
    # visited array to check if value is seen already 
    visited = [False] * (N + 1) 
  
    minimumSwaps = 0
  
    for i in range(2 * N) : 
  
        # If the arr[i] is seen first time 
        if (visited[arr[i]] == False) : 
            visited[arr[i]] = True
  
            # stores the number of swaps required to 
            # find the correct position of current 
            # element's partner 
            count = 0 
  
            for j in range( i + 1, 2 * N) : 
  
                # Increment count only if the current 
                # element has not been visited yet (if is 
                # visited, means it has already been placed 
                # at its correct position) 
                if (visited[arr[j]] == False) :
                    count += 1 
  
                # If current element's partner is found 
                elif (arr[i] == arr[j]) :
                    minimumSwaps += count 
          
    return minimumSwaps
  
  
# Driver Code 
if __name__ == "__main__" :
  
    arr = [ 1, 2, 3, 3, 1, 2 ] 
    N = len(arr) 
    N //= 2
  
    print(findMinimumAdjacentSwaps(arr, N)) 
  
# This code is contributed by Ryuga


C#
// C# Program to find the minimum 
// number of adjacent swaps to 
// arrange similar items together 
using System; 
  
class GFG 
{ 
  
    // Function to find minimum swaps 
    static int findMinimumAdjacentSwaps(int []arr, int N) 
    { 
        // visited array to check
        // if value is seen already 
        bool[] visited = new bool[N + 1]; 
  
        int minimumSwaps = 0; 
  
  
        for (int i = 0; i < 2 * N; i++) 
        { 
  
            // If the arr[i] is seen first time 
            if (visited[arr[i]] == false) 
            { 
                visited[arr[i]] = true; 
  
                // stores the number of swaps required to 
                // find the correct position of current 
                // element's partner 
                int count = 0; 
  
                for (int j = i + 1; j < 2 * N; j++)
                { 
  
                    // Increment count only if the current 
                    // element has not been visited yet (if is 
                    // visited, means it has already been placed 
                    // at its correct position) 
                    if (visited[arr[j]] == false) 
                        count++; 
  
                    // If current element's partner is found 
                    else if (arr[i] == arr[j]) 
                        minimumSwaps += count; 
                } 
            } 
        } 
        return minimumSwaps; 
    } 
  
    // Driver Code 
    public static void Main(String []args) 
    { 
        int []arr = { 1, 2, 3, 3, 1, 2 }; 
        int N = arr.Length; 
        N /= 2; 
  
        Console.WriteLine(findMinimumAdjacentSwaps(arr, N)); 
    } 
} 
  
// This code is contributed by PrinciRaj1992


输出:
5

时间复杂度: O(N 2 )