打印 旋转数组
Problem statement:
问题陈述:
Given an array of N elements and the task is to print the elements of an array after left rotating array elements by d positions.
给定一个由N个元素组成的数组,任务是在将数组元素左旋转 d个位置后打印该数组的元素 。
Input: N, d and next line containing the n elements of array.
输入: N , d和包含数组n个元素的下一行。
Output: Array elements after d rotation.
输出: d旋转后的数组元素。
Example:
例:
Input:
n = 7, d = 2
array elements: 1 2 3 4 5 6 7
Output:
3 4 5 6 7 1 2
Solution:
解:
The naïve approach to solve this problem is to shift the all elements d times but this is a time-consuming process.
解决此问题的幼稚方法是将所有元素移动d次,但这是一个耗时的过程。
We can use a small trick here to print the elements of the array after left rotating d elements.
我们可以在此处使用一个小技巧,在向左旋转d个元素后打印该数组的元素。
Let,
i = ith iteration
D = number of elements to rotate
N = size of array
Then to left rotate array we can use -
arr[i] = arr[(i+D)%N]
C++ Implementation:
C ++实现:
#include <iostream>
using namespace std;
int main()
{
int n,d;
//input value of n and d
cout<<"Enter the value of n and d"<<endl;
cin>>n>>d;
int a[n];
//input array elements
cout<<"enter the array elements : ";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
//print the elements of array after rotation
cout<<"array elements after rotation : ";
for(int i=0;i<n;i++)
{
cout<<a[(i+d)%n]<<" ";
}
return 0;
}
Output
输出量
Enter the value of n and d
7 3
enter the array elements : 1 2 3 4 5 6 7
array elements after rotation : 4 5 6 7 1 2 3
翻译自: https://www.includehelp.com/cpp-programs/print-the-left-rotation-of-the-array.aspx
打印 旋转数组