📌  相关文章
📜  将前 N 个自然数放在不等于它们在数组中的值的索引处

📅  最后修改于: 2021-10-25 11:25:04             🧑  作者: Mango

给定一个整数N ( N > 1 ),任务是将[1, N]范围内的所有整数排列在一个数组中,这样没有一个元素与它们所在的索引(基于 1 的索引)相同在数组中。

例子:

方法:最简单的想法是将N放在第一个索引处,并将其余元素[1, N – 1]放在其余索引处。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to place first N natural
// numbers in an array such that none
// of the values are equal to its indices
void generatepermutation(int N)
{
 
  // Stores the required array
    vector answer;
 
    // Place N at the first position
    answer.push_back(N);
 
    // Iterate the range [1, N)
    for (int i = 1; i < N; i++)
    {
        // Append elements to the sequence
        answer.push_back(i);
    }
 
    // Pritn the sequence
    for(int i:answer) cout << i << " ";
 
}
 
// Driver Code
int main()
{
  int N = 4;
  generatepermutation(N);
 
  return 0;
}
 
// This code is contributed by mohit kumar 29.


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to place first N natural
// numbers in an array such that none
// of the values are equal to its indices
static void generatepermutation(int N)
{
 
  // Stores the required array
    Vector answer = new Vector();
 
    // Place N at the first position
    answer.add(N);
 
    // Iterate the range [1, N)
    for (int i = 1; i < N; i++)
    {
        // Append elements to the sequence
        answer.add(i);
    }
 
    // Pritn the sequence
    for(int i:answer) System.out.print(i+ " ");
}
 
// Driver Code
public static void main(String[] args)
{
  int N = 4;
  generatepermutation(N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python program for the above approach
 
# Function to place first N natural
# numbers in an array such that none
# of the values are equal to its indices
def generatepermutation(N):
 
  # Stores the required array
    answer = []
 
    # Place N at the first position
    answer.append(N)
 
    # Iterate the range [1, N)
    for i in range(1, N):
 
        # Append elements to the sequence
        answer.append(i)
 
    # Pritn the sequence
    print(*answer)
 
 
# Driver Code
N = 4
generatepermutation(N)


C#
// C# program for the above approach
using System;
class GFG
{
 
// Function to place first N natural
// numbers in an array such that none
// of the values are equal to its indices
static void generatepermutation(int N)
{
 
    // Stores the required array
    int[] answer = new int[N];
 
    // Place N at the first position
    answer[0] = N;
 
    // Iterate the range [1, N)
    for (int i = 1; i < N; i++)
    {
       
        // Append elements to the sequence
        answer[i] = i;
    }
 
    // Pritn the sequence
    foreach(int i in answer) Console.Write(i+ " ");
}
 
// Driver Code
static public void Main ()
{
  int N = 4;
  generatepermutation(N);
}
}
 
// This code is contributed by Dharanendra L V


Javascript


输出
4 1 2 3 

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