求范围 [1, N] 中 N 个数字的排列,使得 K 个数字的值与其索引相同
给定一个正整数N和一个整数K使得0 ≤ K ≤ N ,任务是找到 [1, N] 的任何排列A使得A i = i的索引数正好是 K (基于 1索引)。如果不存在这样的排列,则打印-1 。
例子:
Input: N = 3, K = 1
Output: 1 3 2
Explanation: Consider the permutation A = [1, 3, 2]. We have A1=1, A2=3 and A3=2.
So, this permutation has exactly 1 index such that Ai = i.
Input: N = 2, K = 1
Output: -1
Explanation : There are total 2 permutations of [1, 2] which are [1, 2] and [2, 1].
There are 2 indices in [1, 2] and 0 indices in [2, 1] for which Ai = i holds true.
Thus, there doesn’t exist any permutation of [1, 2] with exactly 1 index i for which Ai=i holds true.
方法:可以使用贪心方法来解决任务。最初在它们的索引处精确地固定K个元素,然后随机地将NK个元素放在不同的位置。请按照以下步骤解决问题:
- 以某种方式固定K个位置
- 使剩余的NK数字脱臼
- 将剩余元素循环移位一
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to print permutation
void permutation(int N, int K)
{
if (K == N) {
for (int i = 1; i <= N; i++) {
cout << i << ' ';
}
cout << '\n';
}
else if (K == N - 1) {
cout << "-1" << '\n';
}
else {
for (int i = 1; i <= K; i++) {
cout << i << ' ';
}
for (int i = K + 2; i <= N; i++) {
cout << i << ' ';
}
cout << K + 1 << '\n';
}
}
// Driver Code
int main()
{
int N = 3;
int K = 1;
permutation(N, K);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
public class GFG
{
// Function to print permutation
static void permutation(int N, int K)
{
if (K == N) {
for (int i = 1; i <= N; i++) {
System.out.print(i + " ");
}
System.out.println();
}
else if (K == N - 1) {
System.out.println("-1");
}
else {
for (int i = 1; i <= K; i++) {
System.out.print(i + " ");
}
for (int i = K + 2; i <= N; i++) {
System.out.print(i + " ");
}
System.out.println(K + 1);
}
}
// Driver Code
public static void main(String args[])
{
int N = 3;
int K = 1;
permutation(N, K);
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code for the above approach
# Function to print permutation
def permutation(N, K):
if (K == N):
for i in range(1, N + 1):
print(i, end=" ")
print('')
elif (K == N - 1):
print(-1)
else:
for i in range(1, K + 1):
print(i, end=" ")
for i in range(K + 2, N + 1):
print(i, end=" ")
print(K + 1)
# Driver Code
N = 3;
K = 1;
permutation(N, K);
# This code is contributed by Saurabh Jaiswal
C#
// C# program to implement
// the above approach
using System;
public class GFG {
// Function to print permutation
static void permutation(int N, int K)
{
if (K == N) {
for (int i = 1; i <= N; i++) {
Console.Write(i + " ");
}
Console.WriteLine();
}
else if (K == N - 1) {
Console.WriteLine("-1");
}
else {
for (int i = 1; i <= K; i++) {
Console.Write(i + " ");
}
for (int i = K + 2; i <= N; i++) {
Console.Write(i + " ");
}
Console.Write(K + 1);
}
}
// Driver Code
public static void Main()
{
int N = 3;
int K = 1;
permutation(N, K);
}
}
// This code is contributed by ukasp.
Javascript
1 3 2
时间复杂度: O(N)
辅助空间: O(1)