📌  相关文章
📜  最小化使数组增加所需的相邻元素的交换数

📅  最后修改于: 2021-05-19 17:53:47             🧑  作者: Mango

给定一个由前N个自然数的排列组成的数组A [] ,任务是找到如果数组元素A [i]可与其下一个相邻元素交换,则将A []修改为递增数组所需的最小操作数元素A [i + 1]最多两次。如果无法将数组修改为递增数组,则打印-1

例子:

方法:这个想法是基于观察到的,如果元素A [i]存在于索引i处,那么它必须已经从索引i – 1i – 2中移出。这是因为,要从i – 2的左侧索引移至A [i] ,交换的数量将超过2 。因此,请反向遍历数组,并检查A [i]是否在其正确位置。如果发现不是,请检查A [i – 1]A [i – 2]并相应地更新操作计数。请按照以下步骤解决问题:

  • 使用变量i遍历索引[N – 1,0]上的数组A []
    • 将正确的索引值存储在变量中,例如X表示i +1
    • 如果A [i]当前不在其正确位置,即A [i]不等于X ,则执行以下步骤:
      • 如果A [i – 1]的值等于X ,则将计数递增1交换A [i]A [i-1]
      • 否则,如果A [i – 2]的值等于X ,将计数递增2交换A [i – 2]A [i – 1] ,则A [i – 2]A [i ]
      • 否则,将count的值更新为-1退出循环,因为A [i]不能被交换两次以上
  • 遍历数组后,打印count的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count minimum number of
// operations required to obtain an
// increasing array from given array A[]
void minimumOperations(int A[], int n)
{
    // Store the required result
    int cnt = 0;
 
    // Traverse the array A[]
    for (int i = n - 1; i >= 0; i--) {
 
        // If the current element is not
        // in its correct position
        if (A[i] != (i + 1)) {
 
            // Check if it is present at index i - 1
            if (((i - 1) >= 0)
                && A[i - 1] == (i + 1)) {
                cnt++;
                swap(A[i], A[i - 1]);
            }
 
            // Check if it is present at index i-2
            else if (((i - 2) >= 0)
                     && A[i - 2] == (i + 1)) {
                cnt += 2;
                A[i - 2] = A[i - 1];
                A[i - 1] = A[i];
                A[i] = i + 1;
            }
 
            // Otherwise, print -1 (Since A[i]
            // can not be swapped more than twice)
            else {
                cout << -1;
                return;
            }
        }
    }
 
    // Print the result
    cout << cnt;
}
 
// Driver Code
int main()
{
    // Given array
    int A[] = {7, 3, 2, 1, 4 };
 
    // Store the size of the array
    int n = sizeof(A) / sizeof(A[0]);
 
    minimumOperations(A, n);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to count minimum number of
// operations required to obtain an
// increasing array from given array A[]
static void minimumOperations(int A[], int n)
{
     
    // Store the required result
    int cnt = 0;
 
    // Traverse the array A[]
    for(int i = n - 1; i >= 0; i--)
    {
         
        // If the current element is not
        // in its correct position
        if (A[i] != (i + 1))
        {
             
            // Check if it is present at index i - 1
            if (((i - 1) >= 0) &&
                A[i - 1] == (i + 1))
            {
                cnt++;
                int t = A[i];
                A[i] = A[i-1];
                A[i-1] = t;
            }
 
            // Check if it is present at index i-2
            else if (((i - 2) >= 0) &&
                     A[i - 2] == (i + 1))
            {
                cnt += 2;
                A[i - 2] = A[i - 1];
                A[i - 1] = A[i];
                A[i] = i + 1;
            }
 
            // Otherwise, print -1 (Since A[i]
            // can not be swapped more than twice)
            else
            {
                System.out.println(-1);
                return;
            }
        }
    }
 
    // Print the result
    System.out.println(cnt);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given array
    int A[] = { 7, 3, 2, 1, 4 };
 
    // Store the size of the array
    int n = A.length;
 
    minimumOperations(A, n);
}
}
 
// This code is contributed by souravghosh0416


Python3
# Python 3 program for the above approach
 
# Function to count minimum number of
# operations required to obtain an
# increasing array from given array A[]
def minimumOperations(A, n):
 
    # Store the required result
    cnt = 0
 
    # Traverse the array A[]
    for i in range(n - 1, -1, -1):
 
        # If the current element is not
        # in its correct position
        if (A[i] != (i + 1)):
 
            # Check if it is present at index i - 1
            if (((i - 1) >= 0)
                    and A[i - 1] == (i + 1)):
                cnt += 1
                A[i], A[i - 1] = A[i - 1], A[i]
 
            # Check if it is present at index i-2
            elif (((i - 2) >= 0)
                  and A[i - 2] == (i + 1)):
                cnt += 2
                A[i - 2] = A[i - 1]
                A[i - 1] = A[i]
                A[i] = i + 1
 
            # Otherwise, print -1 (Since A[i]
            # can not be swapped more than twice)
            else:
                print(-1)
                return
 
    # Print the result
    print(cnt)
 
# Driver Code
if __name__ == "__main__":
 
    # Given array
    A = [7, 3, 2, 1, 4]
 
    # Store the size of the array
    n = len(A)
 
    minimumOperations(A, n)
 
    # Thi code is contributed by ukasp.


Javascript


输出:
-1

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