给出三个整N,K和X,该任务是创建长度N SUACH的阵列,其所有的K-长度子阵列的总和模N是X。
例子:
Input: N = 6, K = 3, X = 3
Output: 9 6 6 9 6 6
Explanation:
All subarrays of length 3 and their respective sum%N values are as follows:
[9, 6, 6] Sum = 21 % 6 = 3
[6, 6, 9] sum = 21 % 6 = 3
[6, 9, 6] sum = 21 % 6 = 3
[9, 6, 6] sum = 21 % 6 = 3
Since all its subarrays have sum % N = X (=3), the generated array is valid.
Input: N = 4, K = 2, X = 2
Output: 6 4 6 4
方法:
我们可以观察到,为了使大小为K模N的子数组的总和等于X ,子数组需要具有K – 1个元素等于N和1个元素等于N +X 。
插图:
If N = 6, K = 3, X = 3
Here a K length subarray needs to be a permutation of {9, 6, 6} where 2 (K – 1) elements are divisible by 6 and 1 element has modulo N equal to X( 9%6 = 3)
Sum of subarray % N = (21 % 6) = 3 (same as X)
Hence, each K length
因此,请按照以下步骤解决问题:
- 将i从0迭代到N – 1 ,以打印所需子数组的第i个元素。
- 如果i%K等于0 ,则打印N +X 。否则,对于i的所有其他值,打印N。
- 这确保了每个可能的K长度子数组都有一个和K * N + X。因此,对于所有这样的子阵列,求和模N为X。
下面是上述方法的实现。
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Funtion prints the required array
void createArray(int n, int k, int x)
{
for (int i = 0; i < n; i++) {
// First element of each K
// length subarrays
if (i % k == 0) {
cout << x + n << " ";
}
else {
cout << n << " ";
}
}
}
// Driver Program
int main()
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG{
// Function prints the required array
static void createArray(int n, int k, int x)
{
for(int i = 0; i < n; i++)
{
// First element of each K
// length subarrays
if (i % k == 0)
{
System.out.print((x + n) + " ");
}
else
{
System.out.print(n + " ");
}
}
}
// Driver Code
public static void main(String args[])
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
}
// This code is contributed by Code_Mech
Python3
# Python3 implementation of the
# above approach
# Funtion prints the required array
def createArray(n, k, x):
for i in range(n):
# First element of each K
# length subarrays
if (i % k == 0):
print(x + n, end = " ")
else :
print(n, end = " ")
# Driver code
N = 6
K = 3
X = 3
createArray(N, K, X)
# This code is contributed by Vishal Maurya.
C#
// C# implementation of the above approach
using System;
class GFG{
// Function prints the required array
static void createArray(int n, int k, int x)
{
for(int i = 0; i < n; i++)
{
// First element of each K
// length subarrays
if (i % k == 0)
{
Console.Write((x + n) + " ");
}
else
{
Console.Write(n + " ");
}
}
}
// Driver Code
public static void Main()
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
}
// This code is contributed by Code_Mech
9 6 6 9 6 6
时间复杂度: O(N)
辅助空间: O(1)