📌  相关文章
📜  重新排列给定的数组以获得恰好在X个索引处的正前缀和

📅  最后修改于: 2021-05-06 17:27:18             🧑  作者: Mango

给定由绝对值不同的N个整数和整数K组成的数组arr [] ,任务是通过以下操作找到给定数组的这种排列,以使其在正好K个位置具有正前缀和:

  • 选择两个整数ij,并在索引ij处交换元素的值,其中0≤i,j i≠j
  • 选择一个索引i并更改其符号,即,将0≤i 更改为正值,然后更改为负值。

例子:

方法:可以通过观察一个人可以仅使用第一类操作来获得排序的数组来解决给定的问题。可以使用第二种操作将每个元素更改为正元素。请按照以下步骤解决问题:

  • 通过使用第二次操作使数组的所有值均为正,即,将所有负数的符号翻转为正。
  • 以升序对数组arr []进行排序,并将K设置为等于(N-K)
  • 如果给定数组arr []中K和0的计数之和大于N ,则不可能有这种可能的安排。因此打印“ -1” 。否则,请执行以下操作。
  • 遍历数组 范围为[0,N – 1]并执行以下步骤:
    • 通过第二次操作i元素更改为负数。
    • i递增2 ,将K递减1
    • 如果K等于0,则断开。
  • 检查K是否仍然大于0 ,然后从最后开始遍历数组,直到K大于0 ,然后将每个正元素更改为负,并将K1
  • 完成上述步骤后,将阵列打印为所需的排列。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Funtion to rearrange the array
// according to the given condition
void rearrange(int* a, int n, int x)
{
    // Using 2nd operation making
    // all values positive
    for (int i = 0; i < n; i++)
        a[i] = abs(a[i]);
 
    // Sort the array
    sort(a, a + n);
 
    // Assign K = N - K
    x = n - x;
 
    // Count number of zeros
    int z = count(a, a + n, 0);
 
    // If number of zeros if greater
    if (x > n - z) {
        cout << "-1\n";
        return;
    }
 
    for (int i = 0; i < n && x > 0;
         i += 2) {
 
        // Using 2nd operation convert
        // it into one negative
        a[i] = -a[i];
        x--;
    }
 
    for (int i = n - 1; i >= 0
                        && x > 0;
         i--) {
 
        // Using 2nd operation convert
        // it into one negative
        if (a[i] > 0) {
            a[i] = -a[i];
            x--;
        }
    }
 
    // Print the array
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 0, -2, 4, 5, -3 };
    int K = 3;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    rearrange(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
static int count(int[] a)
{
    int counter = 0;
     
    for(int i = 0; i < a.length; i++)
    {
        if (a[i] == 0)
        {
            counter++;
        }
    }
    return counter;
}
 
// Funtion to rearrange the array
// according to the given condition
static void rearrange(int[] a, int n, int x)
{
     
    // Using 2nd operation making
    // all values positive
    for(int i = 0; i < n; i++)
        a[i] = Math.abs(a[i]);
 
    // Sort the array
    Arrays.sort(a);
 
    // Assign K = N - K
    x = n - x;
      
    // Count number of zeros
    int z = count(a);
 
    // If number of zeros if greater
    if (x > n - z)
    {
        System.out.println("-1");
        return;
    }
 
    for(int i = 0; i < n && x > 0; i += 2)
    {
         
        // Using 2nd operation convert
        // it into one negative
        a[i] = -a[i];
        x--;
    }
 
    for(int i = n - 1; i >= 0 && x > 0; i--)
    {
         
        // Using 2nd operation convert
        // it into one negative
        if (a[i] > 0)
        {
            a[i] = -a[i];
            x--;
        }
    }
 
    // Print the array
    for(int i = 0; i < n; i++)
    {
        System.out.print(a[i] + " ");
    }
}
 
// Driver Code
public static void main (String[] args)
{
    int arr[] = { 0, -2, 4, 5, -3 };
    int K = 3;
    int N = arr.length;
 
    // Function Call
    rearrange(arr, N, K);
}
}
 
// This code is contributed by AnkThon


Python3
# Python3 program for the above approach
 
# Funtion to rearrange the array
# according to the given condition
def rearrange(a, n, x):
   
    # Using 2nd operation making
    # all values positive
    for i in range(n):
        a[i] = abs(a[i])
 
    # Sort the array
    a = sorted(a)
 
    # Assign K = N - K
    x = n - x;
 
    # Count number of zeros
    z = a.count(0)
 
    # If number of zeros if greater
    if (x > n - z):
        print("-1")
        return
    for i in range(0, n, 2):
        if x <= 0:
            break
 
        # Using 2nd operation convert
        # it into one negative
        a[i] = -a[i]
        x -= 1
    for i in range(n - 1, -1, -1):
        if x <= 0:
            break
 
        # Using 2nd operation convert
        # it into one negative
        if (a[i] > 0):
            a[i] = -a[i]
            x -= 1
 
    # Prthe array
    for i in range(n):
        print(a[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
    arr = [0, -2, 4, 5, -3]
    K = 3
    N = len(arr)
 
    # Function Call
    rearrange(arr, N, K)
 
    # This code is co tributed by mohit kumar 29


C#
// C# program for the above approach
using System;
 
class GFG{
     
static int count(int[] a)
{
    int counter = 0;
     
    for(int i = 0; i < a.Length; i++)
    {
        if (a[i] == 0)
        {
            counter++;
        }
    }
    return counter;
}
 
// Funtion to rearrange the array
// according to the given condition
static void rearrange(int[] a, int n, int x)
{
     
    // Using 2nd operation making
    // all values positive
    for(int i = 0; i < n; i++)
        a[i] = Math.Abs(a[i]);
 
    // Sort the array
    Array.Sort(a);
 
    // Assign K = N - K
    x = n - x;
      
    // Count number of zeros
    int z = count(a);
 
    // If number of zeros if greater
    if (x > n - z)
    {
        Console.WriteLine("-1");
        return;
    }
 
    for(int i = 0; i < n && x > 0; i += 2)
    {
         
        // Using 2nd operation convert
        // it into one negative
        a[i] = -a[i];
        x--;
    }
 
    for(int i = n - 1; i >= 0 && x > 0; i--)
    {
         
        // Using 2nd operation convert
        // it into one negative
        if (a[i] > 0)
        {
            a[i] = -a[i];
            x--;
        }
    }
 
    // Print the array
    for(int i = 0; i < n; i++)
    {
        Console.Write(a[i] + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 0, -2, 4, 5, -3 };
    int K = 3;
    int N = arr.Length;
 
    // Function Call
    rearrange(arr, N, K);
}
}
 
// This code is contributed by gauravrajput1


输出:
0 2 -3 4 5

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