📌  相关文章
📜  通过数字逆时针旋转将数组元素重新排列为交替的奇偶序列

📅  最后修改于: 2021-06-25 20:00:48             🧑  作者: Mango

给定由N个正整数组成的数组arr [] ,任务是沿逆时针方向旋转数组元素的数字,以使数组元素的元素呈交替的奇偶或奇偶形式。如果存在多个解决方案,则打印其中任何一种。否则,打印-1

例子:

方法:可以通过将第一个数组元素修改为奇数或偶数来解决上述问题。该阵列元件可以通过将数字转换成一个字符串进行修改,然后旋转根据需要留下的字符串的字符。请按照以下步骤解决问题:

  • 将第一个数组元素重新排列为偶数,并检查是否可以将其余的数组元素交替排列为奇偶数。如果发现是真的,则将数组元素交替重新排列为奇偶数,然后打印数组元素。
  • 否则,将第一个数组元素重新排列为奇数,然后检查是否可以交替将其余的数组元素重新排列为偶数奇数。如果发现是真的,则将剩余的数组元素交替重新排列为偶数,然后打印该数组元素。
  • 否则,打印-1

下面是上述方法的实现:

C++
// c++ program of the above approach
#include 
using namespace std;
 
// Utility function to rotate the digits of
// array elements such that array elements are
// in placed even-odd or odd-even alternately
bool is_possible(vector& arr, bool check)
{
 
    // Checks if array can be converted
    // into even-odd or odd-even form
    bool exists = true;
 
    // Store array elements
    vector cpy = arr;
    bool flag;
    // Traverse the array
    for (int i = 0; i < arr.size(); i++) {
 
        // Check if arr[i] is already
        // at correct position
        if (arr[i] % 2 == check) {
            check = !(check);
            continue;
        }
 
        // Checks if it is possible
        // to modify the number arr[i]
        // by rotating the digits of
        // the number anticlockwise
        flag = false;
 
        // Stores the number arr[i] as
        // string
        string strEle = to_string(arr[i]);
 
        // Traverse over the digits of
        // the current element
        for (int j = 0; j < strEle.size(); j++) {
 
            // Checks if parity of check and
            // current digit is same or not
            if (int(strEle[j]) % 2 == check) {
 
                // Rotates the string by j + 1 times
                // in anticlockwise
                arr[i] = stoi(strEle.substr(j + 1)
                              + strEle.substr(0, j + 1));
 
                // Marks the flag
                // as true and break
                flag = true;
                break;
            }
        }
 
        // If flag is false
        if (flag == false) {
            // Update exists
            exists = false;
            break;
        }
 
        // Changes the
        // parity of check
        check = !(check);
    }
 
    // Checks if arr[] cannot be
    // modified, then returns false
    if (!exists) {
        arr = cpy;
        return false;
    }
 
    // Otherwise, return true
    else
        return true;
}
 
// Function to rotate the digits of array
// elements such that array elements are
// in the form of even-odd or odd-even form
void convert_arr(vector& arr)
{
 
    // If array elements can be arranged
    // in even-odd manner alternately
    if (is_possible(arr, 0)) {
        for (auto& i : arr)
            cout << i << " ";
    }
 
    // If array elements can be arranged
    // in odd-even manner alternately
    else if (is_possible(arr, 1)) {
        for (auto& i : arr)
            cout << i << " ";
    }
 
    // Otherwise, prints -1
    else
        cout << "-1" << endl;
}
 
// Driver Code
int main()
{
 
    vector arr = { 143, 251, 534, 232, 854 };
    convert_arr(arr);
}
 
// This code is contributed by grand_master.


Java
// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Utility function to rotate the digits of
  // array elements such that array elements are
  // in placed even-odd or odd-even alternately
  static boolean is_possible(int arr[], int check)
  {
 
    // Checks if array can be converted
    // into even-odd or odd-even form
    boolean exists = true;
 
    // Store array elements
    int cpy[] = arr.clone();
    boolean flag;
    // Traverse the array
    for (int i = 0; i < arr.length; i++) {
 
      // Check if arr[i] is already
      // at correct position
      if (arr[i] % 2 == check) {
        // Changes the
        // parity of check
        check = (check == 0 ? 1 : 0);
        continue;
      }
 
      // Checks if it is possible
      // to modify the number arr[i]
      // by rotating the digits of
      // the number anticlockwise
      flag = false;
 
      // Stores the number arr[i] as
      // string
      String strEle = Integer.toString(arr[i]);
 
      // Traverse over the digits of
      // the current element
      for (int j = 0; j < strEle.length(); j++) {
 
        // Checks if parity of check and
        // current digit is same or not
        if ((strEle.charAt(j) - '0') % 2 == check) {
 
          // Rotates the string by j + 1 times
          // in anticlockwise
          arr[i] = Integer.parseInt(
            strEle.substring(j + 1)
            + strEle.substring(0, j + 1));
 
          // Marks the flag
          // as true and break
          flag = true;
          break;
        }
      }
 
      // If flag is false
      if (flag == false) {
        // Update exists
        exists = false;
        break;
      }
 
      // Changes the
      // parity of check
      check = (check == 0 ? 1 : 0);
    }
 
    // Checks if arr[] cannot be
    // modified, then returns false
    if (!exists) {
      arr = cpy;
      return false;
    }
 
    // Otherwise, return true
    else
      return true;
  }
 
  // Function to rotate the digits of array
  // elements such that array elements are
  // in the form of even-odd or odd-even form
  static void convert_arr(int arr[])
  {
 
    // If array elements can be arranged
    // in even-odd manner alternately
    if (is_possible(arr, 0)) {
      for (int v : arr) {
        System.out.print(v + " ");
      }
    }
 
    // If array elements can be arranged
    // in odd-even manner alternately
    else if (is_possible(arr, 1)) {
      for (int v : arr) {
        System.out.print(v + " ");
      }
    }
 
    // Otherwise, prints -1
    else
      System.out.println(-1);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    // Given array
    int arr[] = { 143, 251, 534, 232, 854 };
 
    // FUnction call
    convert_arr(arr);
  }
}
 
// This code is contributed by Kingash.


Python3
# Python program of the above approach
 
# Utility function to rotate the digits of
# array elements such that array elements are
# in placed even-odd or odd-even alternately
def is_possible(arr, check):
 
    # Checks if array can be converted
    # into even-odd or odd-even form
    exists = True
 
    # Store array elements
    cpy = arr
 
    # Traverse the array
    for i in range(len(arr)):
 
        # Check if arr[i] is already
        # at correct position
        if (arr[i] % 2 == check):
            check = not(check)
            continue
 
        # Checks if it is possible
        # to modify the number arr[i]
        # by rotating the digits of
        # the number anticlockwise
        flag = False
 
        # Stores the number arr[i] as
        # string
        strEle = str(arr[i])
 
        # Traverse over the digits of
        # the current element
        for j in range(len(strEle)):
 
            # Checks if parity of check and
            # current digit is same or not
            if int(strEle[j]) % 2 == check:
 
                # Rotates the string by j + 1 times
                # in anticlockwise
                arr[i] = int(strEle[j + 1:] + strEle[:j + 1])
 
                # Marks the flag
                # as true and break
                flag = True
                break
 
        # If flag is false
        if flag == False:
 
            # Update exists
            exists = False
            break
 
        # Changes the
        # parity of check
        check = not(check)
 
    # Checks if arr[] cannot be
    # modified, then returns false
    if not exists:
        arr = cpy
        return False
         
         
    # Otherwise, return True
    else:
        return True
 
# Function to rotate the digits of array
# elements such that array elements are
# in the form of even-odd or odd-even form
def convert_arr(arr):
 
    # If array elements can be arranged
    # in even-odd manner alternately
    if(is_possible(arr, 0)):
        print(*arr)
 
    # If array elements can be arranged
    # in odd-even manner alternately
    elif(is_possible(arr, 1)):
        print(*arr)
         
    # Otherwise, prints -1
    else:
        print(-1)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [143, 251, 534, 232, 854]
    convert_arr(arr)
 
    # This code is contributed by ipg2016107.


C#
// C# program of the above approach
using System;
using System.Collections.Generic;
 
 
class GFG{
   
// Utility function to rotate the digits of
// array elements such that array elements are
// in placed even-odd or odd-even alternately
static bool ispossible(List arr, bool check)
{
 
    // Checks if array can be converted
    // into even-odd or odd-even form
    bool exists = true;
 
    // Store array elements
    List cpy = arr;
    bool flag;
    // Traverse the array
    for (int i=0;i arr)
{
 
    // If array elements can be arranged
    // in even-odd manner alternately
    if (ispossible(arr, false)) {
        foreach (int i in arr)
            Console.Write(i +" ");
    }
 
    // If array elements can be arranged
    // in odd-even manner alternately
    else if (ispossible(arr, true)) {
        foreach (int i in arr)
           Console.Write(i + " ");
    }
 
    // Otherwise, prints -1
    else
        Console.Write("-1");
}
 
// Driver Code
public static void Main()
{
    List arr = new List(){143, 251, 534, 232, 854};
    convert_arr(arr);
}
}


输出:
314 251 534 223 854

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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。