给定一个正整数N ,任务是找到一个长度为N的排列,它的任何子数组的按位 OR 大于或等于子数组的长度。
例子:
Input: N = 5
Output: 1 3 5 2 4
Explanation:
Consider the subarray {1, 3, 5} from the permutation {1, 3, 5, 2, $}.
Length of the subarray = 3
Bitwise OR of the subarray = 1 | 3 | 5 = 7 ( which is greater than 3)
Similarly, every subarray of any length smaller than equal to N will satisfy the condition.
Input: 4
Output: 4 3 1 2
方法:实际上任何长度N 的排列都满足要求的条件,基于以下事实:
- 任何一组数字的按位 OR 大于或等于该组中存在的最大数字。
- 由于任何子数组将包含至少一个大于或等于其长度的元素,因此任何排列都满足给定条件。
下面是上述方法的实现:
C++
// C++ implementation of
// the above approach
#include
using namespace std;
// Function to print the
// required permutation
void findPermutation(int N)
{
for(int i = 1; i <= N; i++)
cout << i << " ";
cout << endl;
}
// Driver code
int main()
{
int N = 5;
findPermutation(N);
return 0;
}
Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
// Function to print the
// required permutation
static void findPermutation(int N)
{
for(int i = 1; i <= N; i++)
System.out.print(i + " ");
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
findPermutation(N);
}
}
// This code is contributed by susmitakundugoaldanga
Python3
# Python3 implementation of
# the above approach
# Function to print the
# required permutation
def findPermutation(N):
for i in range(1, N + 1, 1):
print(i, end= " ")
print("\n", end = "")
# Driver code
if __name__ == '__main__':
N = 5
findPermutation(N)
# This code is contributed by ipg2016107.
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Function to print the
// required permutation
static void findPermutation(int N)
{
for(int i = 1; i <= N; i++)
Console.Write(i + " ");
}
// Driver code
public static void Main()
{
int N = 5;
findPermutation(N);
}
}
// This code is contributed by SURENDRA_GANGWAR
Javascript
输出:
1 2 3 4 5
时间复杂度: O(N)
辅助空间: O(1)