给定两个正整数N和K ,任务是按字典顺序找到前N 个自然数的最小排列,使得恰好有K 个完美索引。
An index i in an array is said to be perfect if all the elements at indices smaller than i are smaller than the element at index i.
例子:
Input: N = 10, K = 3
Output: 8 9 10 1 2 3 4 5 6 7
Explanation: There are exactly 3 perfect indices 0, 1 and 2.
Input: N = 12, K = 4
Output: 9 10 11 12 1 2 3 4 5 6 7 8
朴素的方法:这个想法是生成前N 个自然数的所有可能排列,并打印出字典序最小且具有K 个完美索引的排列。
时间复杂度: O(N*N!)
辅助空间: O(1)
高效方法:为了优化上述方法,其思想是观察到最小排列将具有范围[1, N]的最后K 个元素按递增顺序排在前面。其余元素可以按递增顺序附加。请按照以下步骤解决问题:
- 初始化数组A[]以存储前N 个自然数的字典序最小排列。
- 使用变量(例如i )迭代范围[0, K – 1] ,然后更新数组元素A[i]以存储(N – K + 1) + i 。
- 使用变量i迭代范围[K, N – 1]并将数组元素A[i]更新为(i – K + 1) 。
- 完成上述步骤后,打印数组A[] ,该数组包含按字典顺序排列的具有K 个完美索引的最小排列。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to print the lexicographically
// smallest permutation with K perfect indices
void findPerfectIndex(int N, int K)
{
// Iterator to traverse the array
int i = 0;
// Traverse first K array indices
for (; i < K; i++) {
cout << (N - K + 1) + i << " ";
}
// Traverse remaining indices
for (; i < N; i++) {
cout << i - K + 1 << " ";
}
}
// Driver Code
int main()
{
int N = 10, K = 3;
findPerfectIndex(N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to print the lexicographically
// smallest permutation with K perfect indices
static void findPerfectIndex(int N, int K)
{
// Iterator to traverse the array
int i = 0;
// Traverse first K array indices
for (; i < K; i++)
{
System.out.print((N - K + 1) + i+ " ");
}
// Traverse remaining indices
for (; i < N; i++)
{
System.out.print(i - K + 1+ " ");
}
}
// Driver Code
public static void main(String[] args)
{
int N = 10, K = 3;
findPerfectIndex(N, K);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python program for the above approach
# Function to print the lexicographically
# smallest permutation with K perfect indices
def findPerfectIndex(N, K) :
# Iterator to traverse the array
i = 0
# Traverse first K array indices
for i in range(K):
print((N - K + 1) + i, end = " ")
# Traverse remaining indices
for i in range(3, N):
print( i - K + 1, end = " ")
# Driver Code
N = 10
K = 3
findPerfectIndex(N, K)
# This code is contributed by code_hunt.
C#
// C# program for the above approach
using System;
class GFG
{
// Function to print the lexicographically
// smallest permutation with K perfect indices
static void findPerfectIndex(int N, int K)
{
// Iterator to traverse the array
int i = 0;
// Traverse first K array indices
for (; i < K; i++)
{
Console.Write((N - K + 1) + i+ " ");
}
// Traverse remaining indices
for (; i < N; i++)
{
Console.Write(i - K + 1+ " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int N = 10, K = 3;
findPerfectIndex(N, K);
}
}
// This code is contributed by susmitakundugoaldanga.
Javascript
输出:
8 9 10 1 2 3 4 5 6 7
时间复杂度: O(N)
辅助空间: O(1)