📌  相关文章
📜  最多可以通过一次交换实现数组的字典序最小排列

📅  最后修改于: 2021-09-07 03:55:51             🧑  作者: Mango

给定一个数组arr[]表示前N 个自然数的排列,任务是通过交换最多一对数组元素来找到给定数组arr[]可能的字典序最小排列。如果无法按字典顺序缩小数组,则打印“-1”

例子:

方法:这个想法是找到第一个不在其正确位置的数组元素,即arr[i]与索引(i + 1) 不同,并将其与正确位置的元素交换。请按照以下步骤解决此问题:

  • 遍历数组arr[]并找到索引i使得arr[i]不等于(i + 1) ,例如idx ,并将(i + 1)存储在变量中,例如ele
  • 现在,找到ele的索引,比如newIdx
  • 完成上述步骤后,存在两个索引idxnewIdx 。可以通过交换索引idxnewIdx处的元素来形成数组的字典最小排列。现在,打印数组arr[] 。否则,打印“-1”

下面是上述方法的实现:

C++14
// C++ implementation of the above approach
 
#include 
#include 
using namespace std;
 
// Function to print the
// elements of the array arr[]
void print(int arr[], int N)
{
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Function to convert given array to
// lexicographically smallest permutation
// possible by swapping at most one pair
void makeLexicographically(int arr[], int N)
{
    // Stores the index of the first
    // element which is not at its
    // correct position
    int index = 0;
    int temp = 0;
 
    // Checks if any such array
    // element exists or not
    int check = 0;
    int condition = 0;
 
    int element = 0;
 
    // Traverse the given array
    for (int i = 0; i < N; ++i) {
 
        // If element is found at i
        if (element == arr[i]) {
            check = i;
            break;
        }
 
        // If the first array is
        // not in correct position
        else if (arr[i] != i + 1 && check == 0) {
 
            // Store the index of
            // the first elements
            index = i;
            check = 1;
            condition = -1;
 
            // Store the index of
            // the first element
            element = i + 1;
        }
    }
 
    // Swap the pairs
    if (condition == -1) {
 
        temp = arr[index];
        arr[index] = arr[check];
        arr[check] = temp;
    }
 
    // Print the array
    print(arr, N);
}
 
// Driver code
int main()
{
 
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Store the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    makeLexicographically(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to print the
    // elements of the array arr[]
    static void print(int arr[])
    {
        // Traverse the array arr[]
        for (int element : arr) {
            System.out.print(element + " ");
        }
    }
 
    // Function to convert given array to
    // lexicographically smallest permutation
    // possible by swapping at most one pair
    static void makeLexicographically(
        int arr[], int length)
    {
        // Stores the index of the first
        // element which is not at its
        // correct position
        int index = 0;
        int temp = 0;
 
        // Checks if any such array
        // element exists or not
        int check = 0;
        int condition = 0;
 
        int element = 0;
 
        // Traverse the given array
        for (int i = 0; i < length; ++i) {
 
            // If element is found at i
            if (element == arr[i]) {
                check = i;
                break;
            }
 
            // If the first array is
            // not in correct position
            else if (arr[i] != i + 1
                     && check == 0) {
 
                // Store the index of
                // the first elements
                index = i;
                check = 1;
                condition = -1;
 
                // Store the index of
                // the first element
                element = i + 1;
            }
        }
 
        // Swap the pairs
        if (condition == -1) {
 
            temp = arr[index];
            arr[index] = arr[check];
            arr[check] = temp;
        }
 
        // Print the array
        print(arr);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4 };
        int N = arr.length;
 
        makeLexicographically(arr, N);
    }
}


Python3
# Python3 program for the above approach
 
# Function to print the
# elements of the array arr[]
def printt(arr, N) :
     
    # Traverse the array arr[]
    for i in range(N):
        print(arr[i], end = " ")
     
# Function to convert given array to
# lexicographically smallest permutation
# possible by swapping at most one pair
def makeLexicographically(arr, N) :
     
    # Stores the index of the first
    # element which is not at its
    # correct position
    index = 0
    temp = 0
 
    # Checks if any such array
    # element exists or not
    check = 0
    condition = 0
    element = 0
 
    # Traverse the given array
    for i in range(N):
 
        # If element is found at i
        if (element == arr[i]) :
            check = i
            break
         
        # If the first array is
        # not in correct position
        elif (arr[i] != i + 1 and check == 0) :
 
            # Store the index of
            # the first elements
            index = i
            check = 1
            condition = -1
 
            # Store the index of
            # the first element
            element = i + 1
         
    # Swap the pairs
    if (condition == -1) :
        temp = arr[index]
        arr[index] = arr[check]
        arr[check] = temp
     
    # Print the array
    printt(arr, N)
 
# Driver code
 
# Given array
arr = [ 1, 2, 3, 4 ]
 
# Store the size of the array
N = len(arr)
 
makeLexicographically(arr, N)
 
# This code is contributed by code_hunt.


C#
// C# program for the above approach
using System;
 
class GFG {
 
  // Function to print the
  // elements of the array arr[]
  static void print(int[] arr)
  {
     
    // Traverse the array arr[]
    foreach (int element in arr) {
      Console.Write(element + " ");
    }
  }
 
  // Function to convert given array to
  // lexicographically smallest permutation
  // possible by swapping at most one pair
  static void makeLexicographically(
    int []arr, int length)
  {
     
    // Stores the index of the first
    // element which is not at its
    // correct position
    int index = 0;
    int temp = 0;
 
    // Checks if any such array
    // element exists or not
    int check = 0;
    int condition = 0;
 
    int element = 0;
 
    // Traverse the given array
    for (int i = 0; i < length; ++i) {
 
      // If element is found at i
      if (element == arr[i]) {
        check = i;
        break;
      }
 
      // If the first array is
      // not in correct position
      else if (arr[i] != i + 1
               && check == 0) {
 
        // Store the index of
        // the first elements
        index = i;
        check = 1;
        condition = -1;
 
        // Store the index of
        // the first element
        element = i + 1;
      }
    }
 
    // Swap the pairs
    if (condition == -1) {
 
      temp = arr[index];
      arr[index] = arr[check];
      arr[check] = temp;
    }
 
    // Print the array
    print(arr);
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int[] arr = { 1, 2, 3, 4 };
    int N = arr.Length;
 
    makeLexicographically(arr, N);
  }
}
 
// This code is contributed by ukasp.


Javascript


输出:
1 2 3 4

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

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