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

📅  最后修改于: 2021-09-06 05:56:38             🧑  作者: Mango

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

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

例子:

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

  • 使用第二个操作使数组的所有值变为正数,即将所有负数的符号翻转为正数。
  • 按升序对数组 arr[] 进行排序,并设置K等于(N – K)
  • 如果给定数组arr[]K的总和与 0 的计数大于N ,则不可能有任何此类可能的安排。因此打印“-1” 。否则执行以下操作。
  • 遍历数组 range [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


Javascript


输出:
0 2 -3 4 5

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

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