Title Description
I heard that some people think they have mastered the array, then I will test you now!
Gives an array of length n, which requires that every integer in the array be rotated to the right by M (m>=0), and the data from a (A0 a1......an-1) is transformed to (An-m ... aN-1 a0) without using an additional array. an-m-1) (i.e.: The last m-number loop moves to the first m-position).
Now that your program needs to move data as few times as possible, how do you design a moving method?
Input
Line 1th input n (1<=n<=100), M (m>=0)
Line 2nd enter n integers, separated by a space
Output
An array of integers after the output loop shifts the M bit to the right in a row, separated by a space, with no extra spaces at the end of the array.
Sample input
6 12 3 4 5 6 1
Sample output
1 2 3 4 5 6
At first I thought it was very simple, and I thought I could use two arrays. Forgive me for not reading the question carefully. Later thought for a long time, did not want to come out, refer to someone else's code, think the world is really wonderful!
Method One: Move backwards in the M position, which is equivalent to moving backward one after the other until you like it.
Method Two: If the original array: 1 2 3 4 5 6 7 need to shift right 4 times, then we want the result is: 5 6 7 1 2 3 4.
1. Turn 1234 Invert to 4321
2. Turn 567 invert to 765
3. Stitching two inverted arrays: 4321765
4. Reverse the spliced array: 5671234 becomes the result we want.
void RightShift(int* arr,int N, int K){ K = K%N; //对应上文步骤 Reverse(arr,0,K-1); //1 Reverse(arr,K,N-1); //2 Reverse(arr,0,N-1); //4,看到这儿顺便复习下我忘记的reverse函数Because of laziness, the baby only realizes a
#include <iostream>
using namespace Std;
int main ()
{
int a[100];
int n, m,t;
CIN >> n >> m;
for (int i = 0; i < n; i++)
{
CIN >> A[i];
}
while (m--)
{
t = a[n-1];
for (int i = n-1; i>=0; i--)
{
A[i] = a[i-1];
}
A[0] = t;
}
for (int i = 0; i < n-1; i++)
{
cout << A[i] << "";
}
cout << a[n-1] << Endl;
}
It looks like the water problem----the array to the right