给定大小为N的数组和值K ,我们需要围绕该数组右旋转数组。如何快速打印正确的旋转阵列?
例子 :
Input: Array[] = {1, 3, 5, 7, 9}, K = 2.
Output: 7 9 1 3 5
Explanation:
After 1st rotation - {9, 1, 3, 5, 7}
After 2nd rotation - {7, 9, 1, 3, 5}
Input: Array[] = {1, 2, 3, 4, 5}, K = 4.
Output: 2 3 4 5 1
方法:
- 我们首先将K的模数乘以N(K = K%N),因为每旋转N圈后数组将与初始数组相同。
- 现在,我们将数组从i = 0迭代到i = N-1并检查,
- 如果i
,则打印最右边的第K个元素(a [N + i -K])。除此以外, - 在“ K”个元素(a [i – K])之后打印数组。
- 如果i
下面是上述方法的实现。
C++
// C++ implementation of right rotation
// of an array K number of times
#include
using namespace std;
// Function to rightRotate array
void RightRotate(int a[], int n, int k)
{
// If rotation is greater
// than size of array
k = k % n;
for(int i = 0; i < n; i++)
{
if(i < k)
{
// Printing rightmost
// kth elements
cout << a[n + i - k] << " ";
}
else
{
// Prints array after
// 'k' elements
cout << (a[i - k]) << " ";
}
}
cout << "\n";
}
// Driver code
int main()
{
int Array[] = { 1, 2, 3, 4, 5 };
int N = sizeof(Array) / sizeof(Array[0]);
int K = 2;
RightRotate(Array, N, K);
}
// This code is contributed by Surendra_Gangwar
Java
// Java Implementation of Right Rotation
// of an Array K number of times
import java.util.*;
import java.lang.*;
import java.io.*;
class Array_Rotation
{
// Function to rightRotate array
static void RightRotate(int a[],
int n, int k)
{
// If rotation is greater
// than size of array
k=k%n;
for(int i = 0; i < n; i++)
{
if(i
Python3
# Python3 implementation of right rotation
# of an array K number of times
# Function to rightRotate array
def RightRotate(a, n, k):
# If rotation is greater
# than size of array
k = k % n;
for i in range(0, n):
if(i < k):
# Printing rightmost
# kth elements
print(a[n + i - k], end = " ");
else:
# Prints array after
# 'k' elements
print(a[i - k], end = " ");
print("\n");
# Driver code
Array = [ 1, 2, 3, 4, 5 ];
N = len(Array);
K = 2;
RightRotate(Array, N, K);
# This code is contributed by Code_Mech
C#
// C# implementation of right rotation
// of an array K number of times
using System;
class GFG{
// Function to rightRotate array
static void RightRotate(int []a,
int n, int k)
{
// If rotation is greater
// than size of array
k = k % n;
for(int i = 0; i < n; i++)
{
if(i < k)
{
// Printing rightmost
// kth elements
Console.Write(a[n + i - k] + " ");
}
else
{
// Prints array after
// 'k' elements
Console.Write(a[i - k] + " ");
}
}
Console.WriteLine();
}
// Driver code
public static void Main(String []args)
{
int []Array = { 1, 2, 3, 4, 5 };
int N = Array.Length;
int K = 2;
RightRotate(Array, N, K);
}
}
// This code is contributed by Rohit_ranjan
输出:
4 5 1 2 3
时间复杂度:O(n)
辅助空间:O(1)